headless-reaper 0.1.0__tar.gz
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.
- headless_reaper-0.1.0/LICENSE +21 -0
- headless_reaper-0.1.0/PKG-INFO +327 -0
- headless_reaper-0.1.0/README.ko.md +301 -0
- headless_reaper-0.1.0/README.md +303 -0
- headless_reaper-0.1.0/pyproject.toml +55 -0
- headless_reaper-0.1.0/rust/Cargo.lock +112 -0
- headless_reaper-0.1.0/rust/Cargo.toml +18 -0
- headless_reaper-0.1.0/rust/parity.sh +76 -0
- headless_reaper-0.1.0/rust/src/clones.rs +311 -0
- headless_reaper-0.1.0/rust/src/detect.rs +431 -0
- headless_reaper-0.1.0/rust/src/help.txt +32 -0
- headless_reaper-0.1.0/rust/src/main.rs +329 -0
- headless_reaper-0.1.0/rust/src/proc.rs +247 -0
- headless_reaper-0.1.0/rust/src/reap.rs +168 -0
- headless_reaper-0.1.0/rust/src/report.rs +180 -0
- headless_reaper-0.1.0/src/headless_reaper/__init__.py +23 -0
- headless_reaper-0.1.0/src/headless_reaper/__main__.py +6 -0
- headless_reaper-0.1.0/src/headless_reaper/cli.py +260 -0
- headless_reaper-0.1.0/src/headless_reaper/clones.py +176 -0
- headless_reaper-0.1.0/src/headless_reaper/detect.py +375 -0
- headless_reaper-0.1.0/src/headless_reaper/proc.py +192 -0
- headless_reaper-0.1.0/src/headless_reaper/reap.py +166 -0
- headless_reaper-0.1.0/src/headless_reaper/report.py +141 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 El Fenomeno
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: headless-reaper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Classifier: Development Status :: 4 - Beta
|
|
5
|
+
Classifier: Environment :: Console
|
|
6
|
+
Classifier: Intended Audience :: Developers
|
|
7
|
+
Classifier: Operating System :: MacOS
|
|
8
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Rust
|
|
11
|
+
Classifier: Topic :: Software Development :: Testing
|
|
12
|
+
Classifier: Topic :: System :: Systems Administration
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Summary: Find and stop orphaned headless browsers — Chrome, Chromium, Edge, Playwright, Puppeteer, Firefox, WebKit — left behind by tests and automation. Dry run by default.
|
|
15
|
+
Keywords: headless,chrome,chromium,playwright,puppeteer,orphan,zombie,process,memory,cli
|
|
16
|
+
Author: El Fenomeno
|
|
17
|
+
License-Expression: MIT
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
20
|
+
Project-URL: Homepage, https://github.com/elfenomenokim/headless-reaper
|
|
21
|
+
Project-URL: Issues, https://github.com/elfenomenokim/headless-reaper/issues
|
|
22
|
+
Project-URL: Repository, https://github.com/elfenomenokim/headless-reaper
|
|
23
|
+
|
|
24
|
+
# headless-reaper
|
|
25
|
+
|
|
26
|
+
[한국어](https://github.com/elfenomenokim/headless-reaper/blob/main/README.ko.md)
|
|
27
|
+
|
|
28
|
+
Find the headless browsers that a test or automation tool abandoned, and stop them — dry run by default.
|
|
29
|
+
|
|
30
|
+
```console
|
|
31
|
+
$ headless-reaper
|
|
32
|
+
headless-reaper 0.1.0: 1 orphaned group, 8 processes, 705 MB RSS (998 processes scanned)
|
|
33
|
+
|
|
34
|
+
ROOT AGE RSS PIDS PROFILE
|
|
35
|
+
13251 1m 12s 705 MB 8 /tmp/hr-readme/profile
|
|
36
|
+
why: headless, temp profile, remote debugging; launcher gone (reparented to launchd 1)
|
|
37
|
+
|
|
38
|
+
dry run: nothing was killed. Rerun with --kill to terminate these groups.
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
A test launches Chrome in headless mode, then crashes, or calls `process.exit()` before its cleanup runs. The browser is reparented to the init process, keeps its tabs and its renderers, and holds memory for days. One such run left 57 browser processes holding about 24 GB.
|
|
42
|
+
|
|
43
|
+
This tool reads the process table, groups each browser tree under its main process, and kills a tree only when its launcher is gone. It never touches a browser a person is using.
|
|
44
|
+
|
|
45
|
+
## Why
|
|
46
|
+
|
|
47
|
+
- **Only orphans.** A group is killed only when its parent is PID 1, an init process, or a PID that no longer exists. A browser whose launcher is still alive is reported as nothing and left alone.
|
|
48
|
+
- **Only automation.** A target must carry an automation signal: `--headless`, a temp or automation `--user-data-dir`, or a remote debugging switch together with such a profile. A visible browser on a real user profile is never a target, even when it has `--remote-debugging-port`.
|
|
49
|
+
- **Whole trees.** Renderers, GPU and utility helpers are grouped with their main process, so the reported RSS is the memory the tree actually holds, and one command stops all of it.
|
|
50
|
+
- **A safe ladder.** `--kill` sends SIGTERM to every process in the group, waits 10 seconds by default, then sends SIGKILL to what survived. A recycled PID is detected by comparing start times before a signal is sent.
|
|
51
|
+
- **Two editions.** The Rust CLI reads macOS through libproc/sysctl and Linux through `/proc`. The Python reference uses only its standard library (`ps` on macOS, `/proc` on Linux). Neither needs a browser or network to scan.
|
|
52
|
+
- **Optional profile cleanup.** `--remove-profiles` deletes the temp profile of a reaped group only when it is under a temp root, no live browser uses it, and no singleton lock is held.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
```console
|
|
57
|
+
$ pipx install headless-reaper # recommended: isolated, on PATH
|
|
58
|
+
$ uvx headless-reaper --help # or run without installing
|
|
59
|
+
$ pip install headless-reaper # inside a project
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Python 3.9 or newer for the Python package. macOS and Linux have process backends. Both editions report Windows as unsupported and exit 2.
|
|
63
|
+
|
|
64
|
+
### Rust command and Python library in one package
|
|
65
|
+
|
|
66
|
+
The wheel uses maturin `bindings = "bin"`: `pipx install headless-reaper` installs the native `headless-reaper` executable. The same wheel includes `src/headless_reaper`, so `import headless_reaper` and `python -m headless_reaper` still use the pure-Python reference. No Python extension or interpreter is needed by the Rust executable itself.
|
|
67
|
+
|
|
68
|
+
Build from this source with a current stable Rust toolchain:
|
|
69
|
+
|
|
70
|
+
```console
|
|
71
|
+
$ cargo install --path rust --locked
|
|
72
|
+
$ python -m venv .venv
|
|
73
|
+
$ .venv/bin/pip install maturin
|
|
74
|
+
$ .venv/bin/maturin build --release --out dist
|
|
75
|
+
$ .venv/bin/pip install dist/*.whl
|
|
76
|
+
$ .venv/bin/python -c 'import headless_reaper; print(headless_reaper.__version__)'
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
A source install through pip also needs Rust. To run only the reference edition from a checkout, use `PYTHONPATH=src python -m headless_reaper`. The Rust crate is edition 2021; its direct dependencies are `libc` (Unix process APIs) and `serde_json` (JSON encoding). `Cargo.lock` pins their resolved versions.
|
|
80
|
+
|
|
81
|
+
The Rust CLI keeps the reference's flags, environment variables, table, JSON fields and exit codes. `rust/parity.sh` compares both commands, normalizing changing snapshot counters (scanned processes, age and RSS) while preserving their types. Run `rust/parity.sh --json --path /tmp/your-test` to compare a live fixture. Mutating parity requires an empty scope because the first command consumes any target. Use `cargo test --manifest-path rust/Cargo.toml` for the live-parent, default-profile, helper and path-boundary fixtures.
|
|
82
|
+
|
|
83
|
+
`.github/workflows/wheels.yml` prepares macOS arm64/x86_64, manylinux x86_64/aarch64 and Windows x86_64 wheels plus an sdist. It builds artifacts only; it does not upload to PyPI.
|
|
84
|
+
|
|
85
|
+
### Measured editions
|
|
86
|
+
|
|
87
|
+
Measured 2026-11-17, Rust 1.100.0, release builds. Each time is the median of 20 sequential subprocess runs, including process launch. Startup uses `--version`; scan uses `--json --path /tmp/headless-reaper-bench-empty` and still reads the whole process table. Peak RSS is a separate scan measured with `/usr/bin/time` (`-l` on macOS, `-v` on Linux). Filesystem caches were warm; these are two machines and their current process populations, not a general benchmark.
|
|
88
|
+
|
|
89
|
+
| OS / CPU | Edition | Startup (ms) | Scan (ms) | Scan peak RSS (KiB) | Binary (bytes) |
|
|
90
|
+
|---|---|---:|---:|---:|---:|
|
|
91
|
+
| macOS 27 / arm64 | Python 3.12.8 | 36.078 | 122.098 | 23,296 | — |
|
|
92
|
+
| macOS 27 / arm64 | Rust | 2.856 | 11.315 | 3,136 | 620,000 |
|
|
93
|
+
| Ubuntu 24.04 / arm64 | Python 3.12 | 68.953 | 76.615 | 15,144 | — |
|
|
94
|
+
| Ubuntu 24.04 / arm64 | Rust | 0.841 | 5.564 | 1,892 | 594,688 |
|
|
95
|
+
|
|
96
|
+
Rust's lower scan time and RSS justify preferring the native command in scheduled callers, with `python -m headless_reaper` as the fallback when it is missing.
|
|
97
|
+
|
|
98
|
+
On both OSes, a deliberate orphan using a literal throwaway profile under `/tmp` passed table/JSON parity, was reaped with zero running survivors, and had its temp profile removed. A second browser with a live parent was preserved. The macOS fixture had 10 processes; the Linux Chromium headless-shell fixture had 6. The 18-case CLI parity suite passed on macOS, Linux and Windows; Windows Rust was built with the GNU x86_64 toolchain and its unsupported-backend response was exercised. The macOS binary also scanned successfully on a second arm64 Mac.
|
|
99
|
+
|
|
100
|
+
## Usage
|
|
101
|
+
|
|
102
|
+
### Look
|
|
103
|
+
|
|
104
|
+
```console
|
|
105
|
+
$ headless-reaper
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
This is a dry run: nothing is signalled. The header gives the total, then one row per browser tree with its root PID, age, resident memory, process count and profile directory, and a `why` line that names the signals and the reason the launcher counts as gone.
|
|
109
|
+
|
|
110
|
+
### Stop
|
|
111
|
+
|
|
112
|
+
```console
|
|
113
|
+
$ headless-reaper --kill
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
```console
|
|
117
|
+
headless-reaper 0.1.0: 1 orphaned group, 7 processes, 705.1 MB RSS (1003 processes scanned)
|
|
118
|
+
|
|
119
|
+
ROOT AGE RSS PIDS PROFILE
|
|
120
|
+
13251 1m 53s 705.1 MB 7 /tmp/hr-readme/profile
|
|
121
|
+
why: headless, temp profile, remote debugging; launcher gone (reparented to launchd 1)
|
|
122
|
+
|
|
123
|
+
reaped 1 group: sent SIGTERM to 7 of 7 processes, SIGKILL to 0.
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
When a process ignores SIGTERM, the same run ends with `SIGKILL to 1`, and a process that survives even that is named in the output. The exit code is 0 when every target is gone and 1 when one survived.
|
|
127
|
+
|
|
128
|
+
### Scope it
|
|
129
|
+
|
|
130
|
+
A shared machine runs several jobs at once. Two filters keep the sweep inside one of them:
|
|
131
|
+
|
|
132
|
+
```console
|
|
133
|
+
$ headless-reaper --path /srv/app/_tmp
|
|
134
|
+
$ headless-reaper --kill --path /srv/app/_tmp --min-age 30m
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`--path` matches the profile directory, not the executable. Repeat it for more than one prefix. `--min-age` skips trees younger than the given duration, so a browser started a minute ago by a job that is still starting up is left alone. Durations are `30s`, `10m`, `2h`, `1d`, or a plain number of seconds.
|
|
138
|
+
|
|
139
|
+
### Remove the temp profiles
|
|
140
|
+
|
|
141
|
+
```console
|
|
142
|
+
$ headless-reaper --kill --remove-profiles
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```console
|
|
146
|
+
reaped 1 group: sent SIGTERM to 8 of 8 processes, SIGKILL to 0.
|
|
147
|
+
removed temp profile: /tmp/hr-readme/profile
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
A profile is kept, with the reason printed, when it is not under a temp root, when a live browser still uses it, when a `SingletonLock` points at a live process, or when the group left a survivor. Playwright and Puppeteer create a fresh profile per launch, so on a long-lived test machine these directories add up too.
|
|
151
|
+
|
|
152
|
+
### Machine-readable
|
|
153
|
+
|
|
154
|
+
```console
|
|
155
|
+
$ headless-reaper --json | python3 -m json.tool
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"ok": true,
|
|
161
|
+
"version": "0.1.0",
|
|
162
|
+
"platform": "darwin",
|
|
163
|
+
"dry_run": true,
|
|
164
|
+
"scanned": 1013,
|
|
165
|
+
"min_age_seconds": 0,
|
|
166
|
+
"paths": [
|
|
167
|
+
"/tmp/hr-json"
|
|
168
|
+
],
|
|
169
|
+
"totals": {
|
|
170
|
+
"groups": 1,
|
|
171
|
+
"processes": 13,
|
|
172
|
+
"rss_bytes": 1320402944
|
|
173
|
+
},
|
|
174
|
+
"groups": [
|
|
175
|
+
{
|
|
176
|
+
"root_pid": 22308,
|
|
177
|
+
"pids": [
|
|
178
|
+
22308,
|
|
179
|
+
22316,
|
|
180
|
+
22317,
|
|
181
|
+
22319,
|
|
182
|
+
22322,
|
|
183
|
+
22324,
|
|
184
|
+
22325,
|
|
185
|
+
22326,
|
|
186
|
+
22328,
|
|
187
|
+
22329,
|
|
188
|
+
22542,
|
|
189
|
+
22560,
|
|
190
|
+
22596
|
|
191
|
+
],
|
|
192
|
+
"processes": 13,
|
|
193
|
+
"profile": "/tmp/hr-json/profile",
|
|
194
|
+
"signals": [
|
|
195
|
+
"headless",
|
|
196
|
+
"temp profile"
|
|
197
|
+
],
|
|
198
|
+
"reason": "launcher gone (reparented to launchd 1)",
|
|
199
|
+
"age_seconds": 10,
|
|
200
|
+
"age": "10s",
|
|
201
|
+
"rss_bytes": 1320402944,
|
|
202
|
+
"rss": "1.2 GB"
|
|
203
|
+
}
|
|
204
|
+
],
|
|
205
|
+
"reap": null
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
With `--kill`, `reap` becomes an object with `targets`, `sigterm`, `sigkill`, `survivors`, `already_gone`, `denied`, `removed_profiles` and `kept_profiles`. An error prints `{"ok": false, "error": "…"}` and exits non-zero.
|
|
210
|
+
|
|
211
|
+
### Code-signing clones on macOS
|
|
212
|
+
|
|
213
|
+
Chrome can leave a code-signing copy of its app bundle under the user's X temp directory on each launch, especially after it is killed. Chromium, Edge and Chrome for Testing use the same kind of directory. On one measured host, 174 clones accounted for 193 GB apparent size; deleting 171 unused clones increased real free space by only 1.5 GB. Hard links and shared APFS blocks explain why directory totals can be much larger than the physical space recovered. The directories still accumulate and distort disk alerts.
|
|
214
|
+
|
|
215
|
+
```console
|
|
216
|
+
$ headless-reaper --clean-clones # dry run, default min age 10m
|
|
217
|
+
$ headless-reaper --kill --clean-clones --min-age 30m
|
|
218
|
+
$ headless-reaper --all-leftovers # --kill + --clean-clones + --remove-profiles
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
`--clean-clones` alone inspects clones without scanning browser groups or deleting anything. It examines only `code_sign_clone.*` directories under the recognized browser bundle directories in `$(getconf DARWIN_USER_TEMP_DIR)/../X`. It rejects directory symlinks. `--path` still filters browser profiles; it does not expand or change this fixed clone scope. On Linux and Windows clone-only mode says `nothing to do on this OS`; Windows `--all-leftovers` still exits 2 because the browser backend is unsupported.
|
|
222
|
+
|
|
223
|
+
A clone must be older than `--min-age` and unused by running processes. Both editions use native `proc_pidpath` for exact executable paths and `lsof -nP` for open and mapped files. Some same-user protected processes refuse native descriptor-path queries, so those queries cannot replace lsof here. Matching includes file device/inode identity: Chrome clones can hard-link the same executable as `/Applications`, and a pathname alone can name a different link on the next scan. A running browser can therefore preserve several shared clones. Run scheduled cleanup after Chrome quits. A failed open-file scan preserves all clones and exits 1.
|
|
224
|
+
|
|
225
|
+
The dry run reports eligible count and apparent bytes. JSON adds a `clones` object with `candidates`, `kept`, `removed`, `apparent_bytes`, `allocated_bytes`, `reclaimable_bytes_estimate` and `free_space_change_bytes`. Allocated blocks can be shared, so the reclaimable estimate is `null`. A deletion pass reports the observed filesystem free-space change, which can also include concurrent disk activity. It rechecks usage before deleting anything.
|
|
226
|
+
|
|
227
|
+
The local cleanup fixture removed an aged unused clone and preserved an open file reached through a hard link outside the clone, plus a symlink to a directory outside X. The manual Rust sweep changed the fixture-inclusive count from 6 to 5. It did not quit any real Chrome window.
|
|
228
|
+
|
|
229
|
+
### From cron or a launcher
|
|
230
|
+
|
|
231
|
+
The tool is quiet when there is nothing to do, and exits 0 after a successful sweep:
|
|
232
|
+
|
|
233
|
+
```console
|
|
234
|
+
$ 30 4 * * * headless-reaper --kill --min-age 30m
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`--min-age 30m` is the useful guard for a scheduled sweep: a browser that started five minutes ago belongs to a job that is probably still running, and its launcher is still alive anyway.
|
|
238
|
+
|
|
239
|
+
## Options
|
|
240
|
+
|
|
241
|
+
| Option | Default | Meaning |
|
|
242
|
+
|---|---|---|
|
|
243
|
+
| `--kill` | off | Terminate the groups: SIGTERM, wait, then SIGKILL |
|
|
244
|
+
| `--clean-clones` | off | Inspect unused macOS code-sign clones; delete only with `--kill` |
|
|
245
|
+
| `--all-leftovers` | off | `--kill --clean-clones --remove-profiles` |
|
|
246
|
+
| `--min-age DURATION` | `0` (`10m` with clone cleanup) | Skip groups younger than this (`10m`, `2h`, `1d`) |
|
|
247
|
+
| `--path PREFIX` | every path | Only profiles under `PREFIX`; repeatable |
|
|
248
|
+
| `--remove-profiles` | off | With `--kill`, delete the temp profile of a reaped group |
|
|
249
|
+
| `--grace DURATION` | `10s` | Wait between SIGTERM and SIGKILL |
|
|
250
|
+
| `--json` | off | Print one machine-readable object |
|
|
251
|
+
| `--version` | | Print the version |
|
|
252
|
+
|
|
253
|
+
Exit codes: `0` dry run, or every target reaped; `1` a target survived or the process table could not be read; `2` bad usage or an unsupported platform.
|
|
254
|
+
|
|
255
|
+
## What counts as a target
|
|
256
|
+
|
|
257
|
+
A process becomes a group root only when all of these hold:
|
|
258
|
+
|
|
259
|
+
1. Its executable is a browser family the tool knows: Chrome, Chromium, Edge, Chrome for Testing, Playwright's Chromium and headless shell, Puppeteer's Chrome, Firefox (including Playwright's build), or WebKit's mini browser.
|
|
260
|
+
2. It is a browser main process, not a helper. A helper carries `--type=…`, `-contentproc`, or a name such as `… Helper`, `WebKitWebProcess`, `chrome_crashpad_handler`.
|
|
261
|
+
3. It carries an automation signal: `--headless`, or a `--user-data-dir` that is under a temp root or is shaped like an automation profile (`playwright_*dev_profile-*`, `puppeteer_dev_*_profile-*`, `scoped_dir*`), or a `--remote-debugging-*` switch together with such a profile.
|
|
262
|
+
4. Its launcher is gone: the parent is PID 1, a process named `launchd`, `init` or `systemd`, or a PID that no longer exists.
|
|
263
|
+
|
|
264
|
+
The whole tree under that root is the group. A helper that outlived the root and was reparented to init joins the group through its shared profile path instead of becoming a stray group.
|
|
265
|
+
|
|
266
|
+
Never a target:
|
|
267
|
+
|
|
268
|
+
- a browser on macOS's or Linux's real user profile (`~/Library/Application Support/Google/Chrome`, `~/.config/google-chrome`, `~/.mozilla/firefox`, and siblings), even with `--headless`;
|
|
269
|
+
- a visible browser without an automation profile, even with `--remote-debugging-port`;
|
|
270
|
+
- a browser whose parent process is alive.
|
|
271
|
+
|
|
272
|
+
## Environment
|
|
273
|
+
|
|
274
|
+
| Variable | Same as | Example |
|
|
275
|
+
|---|---|---|
|
|
276
|
+
| `HEADLESS_REAPER_MIN_AGE` | `--min-age` | `30m` |
|
|
277
|
+
| `HEADLESS_REAPER_PATH` | `--path` | `/srv/app/_tmp:/srv/other/_tmp` |
|
|
278
|
+
| `HEADLESS_REAPER_GRACE` | `--grace` | `5s` |
|
|
279
|
+
|
|
280
|
+
A command-line flag wins over its variable. `HEADLESS_REAPER_PATH` uses the platform path separator: `:` on macOS and Linux.
|
|
281
|
+
|
|
282
|
+
## Python API
|
|
283
|
+
|
|
284
|
+
```python
|
|
285
|
+
import time
|
|
286
|
+
|
|
287
|
+
from headless_reaper import clean_clones, cleanup_profiles, find_groups, list_processes, reap
|
|
288
|
+
|
|
289
|
+
procs = list_processes()
|
|
290
|
+
groups = find_groups(procs, now=time.time(), min_age=600, paths=("/srv/app/_tmp",))
|
|
291
|
+
for group in groups:
|
|
292
|
+
print(group.root.pid, group.profile, group.signals, group.rss_bytes())
|
|
293
|
+
|
|
294
|
+
result = reap(groups)
|
|
295
|
+
print(result.sigterm, result.sigkill, result.survivors)
|
|
296
|
+
|
|
297
|
+
removed, kept = cleanup_profiles(groups)
|
|
298
|
+
|
|
299
|
+
clones = clean_clones(kill=False, min_age=600) # macOS only; a dry run
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
`list_processes()` returns `Proc` records (`pid`, `ppid`, `rss_bytes`, `started_at`, `state`, `exe`, `argv`). `find_groups()` returns `Group` records with `root`, `members`, `profile`, `signals`, `reason`, and helpers `pids`, `rss_bytes()`, `age_seconds(now)`.
|
|
303
|
+
|
|
304
|
+
## Limits
|
|
305
|
+
|
|
306
|
+
Tested on:
|
|
307
|
+
|
|
308
|
+
- macOS 27, arm64, Google Chrome 157: a deliberate orphan made by launching headless Chrome from a short-lived parent, then a second one from a live parent. The first was found and stopped, the second was left alone, and the machine's normal Chrome windows were untouched.
|
|
309
|
+
- Ubuntu 24.04, arm64, Playwright Chromium headless shell 159 and Playwright Firefox 159: a deliberate orphan for each, found, stopped, and its temp profile removed. The real Playwright launch arguments (`--headless`, `--user-data-dir=/tmp/playwright_chromiumdev_profile-…`, `--remote-debugging-pipe`; `-headless -profile …` for Firefox) are what the detector matches.
|
|
310
|
+
|
|
311
|
+
Not tested:
|
|
312
|
+
|
|
313
|
+
- **Windows browser detection.** Both editions deliberately have no backend. The Rust GNU x86_64 build and the matching exit-2 response were checked; no browser is scanned or killed there.
|
|
314
|
+
- **WebKit live.** The Playwright WebKit build on the test host was missing its GTK 4 libraries, so only its argument shape (`pw_run.sh --headless --user-data-dir=/tmp/playwright_webkitdev_profile-…`) was checked against the detector, not a running browser.
|
|
315
|
+
- **macOS/Linux x86_64.** Their process backends have not been run on x86_64. The Windows x86_64 build only exercises the unsupported-platform branch.
|
|
316
|
+
- **Python macOS `ps` and spaces.** The reference cannot recover a profile path containing spaces from `ps`. Rust uses `KERN_PROCARGS2` for exact argv and libproc for PID, parent, start time and RSS. Linux reads exact argv in both editions. An inaccessible macOS PID is retained as an unknown process so its children cannot be mistaken for orphans.
|
|
317
|
+
- **A browser started directly by launchd or systemd.** Its parent is the init process, so it looks exactly like an orphan. Scope it with `--path`, or give it a `--min-age` larger than its restart interval.
|
|
318
|
+
- **A visible automation browser on a real profile.** Puppeteer with `headless: false` and a project profile under your home directory is not reaped, even if its launcher died. That is deliberate: the tool prefers to leave a visible window running over closing one a person may be using. Put such profiles under a temp root if you want them swept.
|
|
319
|
+
|
|
320
|
+
## Agents
|
|
321
|
+
|
|
322
|
+
If you are an AI agent asked to clean up leftover browsers, read [AGENTS.md](https://github.com/elfenomenokim/headless-reaper/blob/main/AGENTS.md). The Claude Code skill lives in [`skill/headless-reaper/SKILL.md`](https://github.com/elfenomenokim/headless-reaper/blob/main/skill/headless-reaper/SKILL.md); install it by copying that folder to `~/.claude/skills/headless-reaper/`.
|
|
323
|
+
|
|
324
|
+
## License
|
|
325
|
+
|
|
326
|
+
MIT — see [LICENSE](https://github.com/elfenomenokim/headless-reaper/blob/main/LICENSE).
|
|
327
|
+
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# headless-reaper
|
|
2
|
+
|
|
3
|
+
[English](https://github.com/elfenomenokim/headless-reaper/blob/main/README.md)
|
|
4
|
+
|
|
5
|
+
테스트나 자동화 도구가 놓고 간 헤드리스 브라우저를 찾아서 정리합니다. 기본값은 드라이 런입니다.
|
|
6
|
+
|
|
7
|
+
```console
|
|
8
|
+
$ headless-reaper
|
|
9
|
+
headless-reaper 0.1.0: 1 orphaned group, 8 processes, 705 MB RSS (998 processes scanned)
|
|
10
|
+
|
|
11
|
+
ROOT AGE RSS PIDS PROFILE
|
|
12
|
+
13251 1m 12s 705 MB 8 /tmp/hr-readme/profile
|
|
13
|
+
why: headless, temp profile, remote debugging; launcher gone (reparented to launchd 1)
|
|
14
|
+
|
|
15
|
+
dry run: nothing was killed. Rerun with --kill to terminate these groups.
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
테스트가 헤드리스 크롬을 띄운 뒤 죽거나, 정리 코드가 돌기 전에 `process.exit()`를 부르면 브라우저가 남습니다. 부모가 사라진 브라우저는 init 프로세스로 옮겨 붙고, 탭과 렌더러를 그대로 유지한 채 며칠씩 메모리를 잡고 있습니다. 실제로 한 번은 이렇게 남은 브라우저 프로세스 57개가 24GB쯤을 붙잡고 있었습니다.
|
|
19
|
+
|
|
20
|
+
이 도구는 프로세스 목록을 읽어 브라우저 한 그루를 대표 프로세스 아래로 묶고, 그 프로세스를 띄운 부모가 사라졌을 때만 정리합니다. 사람이 쓰고 있는 브라우저는 건드리지 않습니다.
|
|
21
|
+
|
|
22
|
+
## 이렇게 동작합니다
|
|
23
|
+
|
|
24
|
+
- **부모가 없는 것만.** 부모가 PID 1이거나 init 프로세스이거나, 아니면 이미 없는 PID일 때만 대상으로 봅니다. 부모가 살아 있는 브라우저는 목록에 아예 올리지 않습니다.
|
|
25
|
+
- **자동화가 띄운 것만.** `--headless`가 있거나, 임시·자동화용 `--user-data-dir`이 있거나, 그런 프로필에 `--remote-debugging-*`이 함께 있을 때만 대상입니다. 사람이 쓰는 실제 프로필의 브라우저는 `--remote-debugging-port`가 붙어 있어도 대상이 아닙니다.
|
|
26
|
+
- **한 그루째 묶어서.** 렌더러, GPU, 유틸리티 프로세스를 대표 프로세스와 함께 묶습니다. 그래서 표시되는 RSS가 그 브라우저가 실제로 쓰는 메모리이고, 한 번에 전부 정리됩니다.
|
|
27
|
+
- **안전한 순서.** `--kill`은 그룹의 모든 프로세스에 SIGTERM을 보내고, 기본 10초를 기다린 뒤 살아남은 것에 SIGKILL을 보냅니다. 시그널을 보내기 전에 시작 시각을 비교하므로 PID가 재사용된 프로세스는 건드리지 않습니다.
|
|
28
|
+
- **두 가지 구현.** Rust 명령은 macOS에서 libproc/sysctl, Linux에서 `/proc`를 읽습니다. Python 참조 구현은 표준 라이브러리만 씁니다. 조회할 때 브라우저나 네트워크가 필요하지 않습니다.
|
|
29
|
+
- **프로필 정리는 선택.** `--remove-profiles`는 정리한 그룹의 임시 프로필을, 임시 경로 안에 있고 살아 있는 브라우저가 쓰지 않고 싱글턴 락도 없을 때만 지웁니다.
|
|
30
|
+
|
|
31
|
+
## 설치
|
|
32
|
+
|
|
33
|
+
```console
|
|
34
|
+
$ pipx install headless-reaper # 권장: 격리 설치, PATH에 명령이 생깁니다
|
|
35
|
+
$ uvx headless-reaper --help # 설치 없이 한 번만 실행
|
|
36
|
+
$ pip install headless-reaper # 프로젝트 안에서
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Python 패키지는 Python 3.9 이상이 필요합니다. macOS와 Linux에서 프로세스를 조회합니다. 두 구현 모두 Windows에서는 미지원 메시지와 종료 코드 2를 반환합니다.
|
|
40
|
+
|
|
41
|
+
### 한 패키지에 Rust 명령과 Python 라이브러리
|
|
42
|
+
|
|
43
|
+
maturin의 `bindings = "bin"`으로 만든 wheel은 `headless-reaper` Rust 실행 파일을 설치합니다. 같은 wheel에 `src/headless_reaper`도 들어갑니다. 따라서 `import headless_reaper`와 `python -m headless_reaper`는 기존 Python 참조 구현을 그대로 사용합니다. Rust 실행 파일 자체에는 Python 인터프리터가 필요하지 않습니다.
|
|
44
|
+
|
|
45
|
+
소스에서 빌드하려면 현재 stable Rust 도구 체인을 설치합니다.
|
|
46
|
+
|
|
47
|
+
```console
|
|
48
|
+
$ cargo install --path rust --locked
|
|
49
|
+
$ python -m venv .venv
|
|
50
|
+
$ .venv/bin/pip install maturin
|
|
51
|
+
$ .venv/bin/maturin build --release --out dist
|
|
52
|
+
$ .venv/bin/pip install dist/*.whl
|
|
53
|
+
$ .venv/bin/python -c 'import headless_reaper; print(headless_reaper.__version__)'
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
pip 소스 설치에도 Rust가 필요합니다. Python 구현만 실행하려면 체크아웃에서 `PYTHONPATH=src python -m headless_reaper`를 사용합니다. Rust crate는 edition 2021이며 직접 의존성은 Unix API용 `libc`와 JSON 출력용 `serde_json`입니다. 해석된 버전은 `Cargo.lock`에 고정합니다.
|
|
57
|
+
|
|
58
|
+
옵션, 환경 변수, 표, JSON 필드와 종료 코드는 두 구현이 같습니다. `rust/parity.sh`는 두 명령의 출력을 비교합니다. 조회 시점에 따라 달라지는 프로세스 수, 유지 시간과 RSS는 형식을 검사한 뒤 정규화합니다. 실제 테스트 프로필은 `rust/parity.sh --json --path /tmp/your-test`로 비교합니다. 정리 명령을 차례로 두 번 실행하면 첫 명령이 대상을 없애므로, `--kill` 비교는 대상이 없는 범위에서만 허용합니다. `cargo test --manifest-path rust/Cargo.toml`은 살아 있는 부모, 실제 사용자 프로필, 보조 프로세스와 경로 경계를 검사합니다.
|
|
59
|
+
|
|
60
|
+
`.github/workflows/wheels.yml`은 macOS arm64/x86_64, manylinux x86_64/aarch64, Windows x86_64 wheel과 sdist를 만듭니다. 결과물을 빌드할 뿐 PyPI에는 업로드하지 않습니다.
|
|
61
|
+
|
|
62
|
+
### 두 구현의 측정값
|
|
63
|
+
|
|
64
|
+
2026-11-17에 Rust 1.100.0 release 빌드로 측정했습니다. 시간은 프로세스 실행을 포함한 20회 순차 실행의 중앙값입니다. 시작은 `--version`, 조회는 `--json --path /tmp/headless-reaper-bench-empty`를 사용했습니다. 경로를 좁혀도 프로세스 목록 전체를 읽습니다. 최대 RSS는 별도 조회 1회에서 `/usr/bin/time`으로 측정했습니다. 파일 캐시가 준비된 상태이며, 당시 두 기기의 프로세스 구성에 대한 결과입니다.
|
|
65
|
+
|
|
66
|
+
| OS / CPU | 구현 | 시작 (ms) | 조회 (ms) | 조회 최대 RSS (KiB) | 바이너리 (bytes) |
|
|
67
|
+
|---|---|---:|---:|---:|---:|
|
|
68
|
+
| macOS 27 / arm64 | Python 3.12.8 | 36.078 | 122.098 | 23,296 | — |
|
|
69
|
+
| macOS 27 / arm64 | Rust | 2.856 | 11.315 | 3,136 | 620,000 |
|
|
70
|
+
| Ubuntu 24.04 / arm64 | Python 3.12 | 68.953 | 76.615 | 15,144 | — |
|
|
71
|
+
| Ubuntu 24.04 / arm64 | Rust | 0.841 | 5.564 | 1,892 | 594,688 |
|
|
72
|
+
|
|
73
|
+
정기 호출에서는 조회 시간과 RSS가 낮은 Rust 명령을 우선 사용합니다. 실행 파일이 없으면 `python -m headless_reaper`로 돌아갈 수 있습니다.
|
|
74
|
+
|
|
75
|
+
두 OS에서 `/tmp` 아래의 명시적인 일회용 프로필로 고아 브라우저를 만들었습니다. 표·JSON 비교를 통과했고, 정리 후 실행 중인 대상은 0개였으며 임시 프로필도 삭제했습니다. 살아 있는 부모가 띄운 두 번째 브라우저는 유지했습니다. macOS 대상은 10개 프로세스, Linux Chromium headless shell 대상은 6개였습니다. 18개 CLI 비교는 macOS·Linux·Windows에서 통과했습니다. Windows는 GNU x86_64 도구 체인으로 빌드하고 미지원 응답까지 실행했습니다. macOS 실행 파일은 두 번째 arm64 Mac에서도 조회했습니다.
|
|
76
|
+
|
|
77
|
+
## 쓰는 법
|
|
78
|
+
|
|
79
|
+
### 먼저 보기
|
|
80
|
+
|
|
81
|
+
```console
|
|
82
|
+
$ headless-reaper
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
드라이 런이라 아무 시그널도 보내지 않습니다. 머리줄에 전체 합계가 나오고, 브라우저 한 그루마다 대표 PID, 유지 시간, 메모리(RSS), 프로세스 수, 프로필 경로가 한 줄로 나옵니다. 그 아래 `why` 줄은 어떤 신호 때문에, 그리고 왜 부모가 사라졌다고 보는지 적습니다.
|
|
86
|
+
|
|
87
|
+
### 정리하기
|
|
88
|
+
|
|
89
|
+
```console
|
|
90
|
+
$ headless-reaper --kill
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```console
|
|
94
|
+
headless-reaper 0.1.0: 1 orphaned group, 7 processes, 705.1 MB RSS (1003 processes scanned)
|
|
95
|
+
|
|
96
|
+
ROOT AGE RSS PIDS PROFILE
|
|
97
|
+
13251 1m 53s 705.1 MB 7 /tmp/hr-readme/profile
|
|
98
|
+
why: headless, temp profile, remote debugging; launcher gone (reparented to launchd 1)
|
|
99
|
+
|
|
100
|
+
reaped 1 group: sent SIGTERM to 7 of 7 processes, SIGKILL to 0.
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
SIGTERM을 무시하는 프로세스가 있으면 같은 실행이 `SIGKILL to 1`로 끝납니다. SIGKILL까지 버티는 프로세스는 출력에 PID로 나옵니다. 종료 코드는 모두 정리했으면 0, 하나라도 남았으면 1입니다.
|
|
104
|
+
|
|
105
|
+
### 범위 좁히기
|
|
106
|
+
|
|
107
|
+
여러 작업이 같이 도는 머신이라면 두 가지로 범위를 좁힙니다.
|
|
108
|
+
|
|
109
|
+
```console
|
|
110
|
+
$ headless-reaper --path /srv/app/_tmp
|
|
111
|
+
$ headless-reaper --kill --path /srv/app/_tmp --min-age 30m
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`--path`는 실행 파일이 아니라 프로필 디렉터리를 봅니다. 여러 개를 쓰려면 옵션을 반복합니다. `--min-age`는 그 시간보다 최근에 시작한 그루를 건너뜁니다. 방금 시작한 브라우저는 아직 준비 중인 작업의 것일 수 있기 때문입니다. 시간은 `30s`, `10m`, `2h`, `1d` 또는 초 단위 숫자로 씁니다.
|
|
115
|
+
|
|
116
|
+
### 임시 프로필까지 지우기
|
|
117
|
+
|
|
118
|
+
```console
|
|
119
|
+
$ headless-reaper --kill --remove-profiles
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
```console
|
|
123
|
+
reaped 1 group: sent SIGTERM to 7 of 7 processes, SIGKILL to 0.
|
|
124
|
+
removed temp profile: /tmp/hr-readme/profile
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
임시 경로 밖이거나, 살아 있는 브라우저가 아직 쓰거나, `SingletonLock`이 살아 있는 프로세스를 가리키거나, 그룹에 살아남은 프로세스가 있으면 프로필을 지우지 않고 이유를 같이 출력합니다. Playwright와 Puppeteer는 실행할 때마다 새 프로필을 만들기 때문에, 오래 쓰는 테스트 머신에서는 이 디렉터리도 함께 쌓입니다.
|
|
128
|
+
|
|
129
|
+
### 기계가 읽기
|
|
130
|
+
|
|
131
|
+
```console
|
|
132
|
+
$ headless-reaper --json | python3 -m json.tool
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
```json
|
|
136
|
+
{
|
|
137
|
+
"ok": true,
|
|
138
|
+
"version": "0.1.0",
|
|
139
|
+
"platform": "darwin",
|
|
140
|
+
"dry_run": true,
|
|
141
|
+
"scanned": 1013,
|
|
142
|
+
"min_age_seconds": 0,
|
|
143
|
+
"paths": [
|
|
144
|
+
"/tmp/hr-json"
|
|
145
|
+
],
|
|
146
|
+
"totals": {
|
|
147
|
+
"groups": 1,
|
|
148
|
+
"processes": 13,
|
|
149
|
+
"rss_bytes": 1320402944
|
|
150
|
+
},
|
|
151
|
+
"groups": [
|
|
152
|
+
{
|
|
153
|
+
"root_pid": 22308,
|
|
154
|
+
"pids": [
|
|
155
|
+
22308,
|
|
156
|
+
22316,
|
|
157
|
+
22317,
|
|
158
|
+
22319,
|
|
159
|
+
22322,
|
|
160
|
+
22324,
|
|
161
|
+
22325,
|
|
162
|
+
22326,
|
|
163
|
+
22328,
|
|
164
|
+
22329,
|
|
165
|
+
22542,
|
|
166
|
+
22560,
|
|
167
|
+
22596
|
|
168
|
+
],
|
|
169
|
+
"processes": 13,
|
|
170
|
+
"profile": "/tmp/hr-json/profile",
|
|
171
|
+
"signals": [
|
|
172
|
+
"headless",
|
|
173
|
+
"temp profile"
|
|
174
|
+
],
|
|
175
|
+
"reason": "launcher gone (reparented to launchd 1)",
|
|
176
|
+
"age_seconds": 10,
|
|
177
|
+
"age": "10s",
|
|
178
|
+
"rss_bytes": 1320402944,
|
|
179
|
+
"rss": "1.2 GB"
|
|
180
|
+
}
|
|
181
|
+
],
|
|
182
|
+
"reap": null
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`--kill`과 함께 쓰면 `reap`이 객체가 되고 `targets`, `sigterm`, `sigkill`, `survivors`, `already_gone`, `denied`, `removed_profiles`, `kept_profiles`가 들어갑니다. 오류일 때는 `{"ok": false, "error": "…"}`를 출력하고 0이 아닌 코드로 끝납니다.
|
|
187
|
+
|
|
188
|
+
### cron이나 실행기에서 쓰기
|
|
189
|
+
|
|
190
|
+
정리할 것이 없으면 한 줄만 남기고, 정리가 끝나면 0으로 끝납니다.
|
|
191
|
+
|
|
192
|
+
```console
|
|
193
|
+
$ 30 4 * * * headless-reaper --kill --min-age 30m
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
정해진 시각에 도는 정리라면 `--min-age 30m`이 쓸 만한 안전장치입니다. 5분 전에 시작한 브라우저는 대개 아직 도는 작업의 것이고, 어차피 부모도 살아 있습니다.
|
|
197
|
+
|
|
198
|
+
### macOS 코드 서명 복제본
|
|
199
|
+
|
|
200
|
+
Chrome은 실행할 때 사용자의 X 임시 디렉터리에 앱 번들의 코드 서명 복제본을 만들 수 있습니다. 강제로 종료하면 이 디렉터리가 남기도 합니다. Chromium·Edge·Chrome for Testing도 같은 종류의 경로를 씁니다. 한 기기에서 복제본 174개가 겉보기 용량 193 GB를 차지했습니다. 사용하지 않는 171개를 지운 뒤 실제 여유 공간은 1.5 GB 늘었습니다. 하드 링크와 APFS 공유 블록 때문에 디렉터리 합계가 실제 회수 용량보다 클 수 있습니다. 그래도 디렉터리가 계속 쌓이고 디스크 경보를 왜곡합니다.
|
|
201
|
+
|
|
202
|
+
```console
|
|
203
|
+
$ headless-reaper --clean-clones # 드라이 런, 기본 최소 유지 시간 10분
|
|
204
|
+
$ headless-reaper --kill --clean-clones --min-age 30m
|
|
205
|
+
$ headless-reaper --all-leftovers # --kill + --clean-clones + --remove-profiles
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`--clean-clones`만 쓰면 브라우저 그룹 조회나 삭제 없이 복제본만 확인합니다. 범위는 `$(getconf DARWIN_USER_TEMP_DIR)/../X` 안에서 지원하는 브라우저의 `code_sign_clone.*` 디렉터리로 고정합니다. 디렉터리 심볼릭 링크는 건너뜁니다. `--path`는 브라우저 프로필만 좁히며 복제본 범위를 바꾸지 않습니다. Linux와 Windows의 복제본 전용 조회는 `nothing to do on this OS`라고 알립니다. Windows의 `--all-leftovers`는 브라우저 백엔드가 없어 종료 코드 2를 반환합니다.
|
|
209
|
+
|
|
210
|
+
복제본은 `--min-age`보다 오래되었고 실행 중인 프로세스가 쓰지 않을 때만 삭제합니다. 두 구현 모두 실행 파일의 정확한 경로는 `proc_pidpath`, 열린 파일과 메모리 매핑은 `lsof -nP`로 읽습니다. macOS는 같은 사용자의 보호된 프로세스에도 일부 네이티브 파일 경로 조회를 거부하므로, 그 조회만으로 lsof를 대체할 수 없습니다. 경로뿐 아니라 파일의 장치·inode도 비교합니다. Chrome 복제본의 실행 파일은 `/Applications`의 실행 파일과 하드 링크로 연결될 수 있습니다. 따라서 경로만 비교하면 다음 조회에서 다른 링크 이름이 나올 수 있습니다. 실행 중인 브라우저가 여러 복제본을 함께 보존할 수 있으므로, 정기 정리는 Chrome이 종료된 다음에 실행합니다. 열린 파일 조회가 실패하면 모든 복제본을 보존하고 종료 코드 1을 반환합니다.
|
|
211
|
+
|
|
212
|
+
드라이 런은 정리 가능한 개수와 겉보기 용량을 표시합니다. JSON의 `clones`에는 `candidates`, `kept`, `removed`, `apparent_bytes`, `allocated_bytes`, `reclaimable_bytes_estimate`, `free_space_change_bytes`가 들어갑니다. 할당 블록도 공유될 수 있으므로 삭제 전 실제 회수 예상치는 `null`입니다. 삭제 후에는 파일시스템 여유 공간의 관측 변화를 표시합니다. 이 값에는 같은 시간의 다른 디스크 활동도 섞일 수 있습니다. 삭제 직전에 사용 여부를 다시 확인합니다.
|
|
213
|
+
|
|
214
|
+
로컬 검사에서는 오래된 일회용 복제본을 삭제했습니다. 복제본 밖의 하드 링크를 통해 열어 둔 파일과 X 밖 디렉터리를 가리키는 심볼릭 링크는 보존했습니다. Rust 수동 정리에서 테스트 디렉터리를 포함한 개수는 6개에서 5개가 되었습니다. 실제 Chrome 창은 종료하지 않았습니다.
|
|
215
|
+
|
|
216
|
+
## 옵션
|
|
217
|
+
|
|
218
|
+
| 옵션 | 기본값 | 뜻 |
|
|
219
|
+
|---|---|---|
|
|
220
|
+
| `--kill` | 끔 | 그룹을 정리합니다. SIGTERM, 대기, 그다음 SIGKILL |
|
|
221
|
+
| `--clean-clones` | 꺼짐 | macOS 코드 서명 복제본 조회, `--kill`과 함께 삭제 |
|
|
222
|
+
| `--all-leftovers` | 꺼짐 | `--kill --clean-clones --remove-profiles` |
|
|
223
|
+
| `--min-age DURATION` | `0` (복제본 정리는 `10m`) | 이 시간보다 최근에 시작한 그룹은 건너뜁니다 (`10m`, `2h`, `1d`) |
|
|
224
|
+
| `--path PREFIX` | 모든 경로 | `PREFIX` 아래 프로필만 봅니다. 여러 번 쓸 수 있습니다 |
|
|
225
|
+
| `--remove-profiles` | 끔 | `--kill`과 함께, 정리한 그룹의 임시 프로필을 지웁니다 |
|
|
226
|
+
| `--grace DURATION` | `10s` | SIGTERM과 SIGKILL 사이에 기다리는 시간 |
|
|
227
|
+
| `--json` | 끔 | 기계가 읽을 객체 하나를 출력합니다 |
|
|
228
|
+
| `--version` | | 버전 출력 |
|
|
229
|
+
|
|
230
|
+
종료 코드: `0`은 드라이 런이거나 모두 정리됨, `1`은 남은 프로세스가 있거나 프로세스 목록을 읽지 못함, `2`는 잘못된 사용법이거나 지원하지 않는 플랫폼입니다.
|
|
231
|
+
|
|
232
|
+
## 무엇을 대상으로 보나
|
|
233
|
+
|
|
234
|
+
아래 조건을 모두 만족할 때만 그룹의 대표 프로세스가 됩니다.
|
|
235
|
+
|
|
236
|
+
1. 실행 파일이 아는 브라우저 계열입니다. 크롬, 크로미움, 엣지, Chrome for Testing, Playwright의 크로미움과 헤드리스 셸, Puppeteer의 크롬, 파이어폭스(Playwright 빌드 포함), WebKit 미니 브라우저가 여기에 속합니다.
|
|
237
|
+
2. 브라우저 본체입니다. 도우미 프로세스는 제외합니다. `--type=…`이나 `-contentproc`이 있거나, 이름에 `… Helper`, `WebKitWebProcess`, `chrome_crashpad_handler`가 들어가면 도우미입니다.
|
|
238
|
+
3. 자동화 신호가 있습니다. `--headless`, 또는 임시 경로나 자동화 모양(`playwright_*dev_profile-*`, `puppeteer_dev_*_profile-*`, `scoped_dir*`)인 `--user-data-dir`, 또는 그런 프로필과 함께 있는 `--remote-debugging-*`이 있어야 합니다.
|
|
239
|
+
4. 부모가 사라졌습니다. 부모가 PID 1이거나, 이름이 `launchd`, `init`, `systemd`인 프로세스이거나, 이미 없는 PID입니다.
|
|
240
|
+
|
|
241
|
+
그 대표 프로세스 아래의 프로세스 전체가 한 그룹입니다. 대표가 죽은 뒤 init으로 옮겨 간 도우미 프로세스는 같은 프로필 경로를 통해 그룹에 합쳐지고, 따로 떨어진 그룹이 되지 않습니다.
|
|
242
|
+
|
|
243
|
+
대상이 되지 않는 것:
|
|
244
|
+
|
|
245
|
+
- macOS나 Linux의 실제 사용자 프로필(`~/Library/Application Support/Google/Chrome`, `~/.config/google-chrome`, `~/.mozilla/firefox` 등)을 쓰는 브라우저. `--headless`가 붙어 있어도 대상이 아닙니다.
|
|
246
|
+
- 자동화용 프로필이 없는 화면 있는 브라우저. `--remote-debugging-port`가 있어도 대상이 아닙니다.
|
|
247
|
+
- 부모 프로세스가 살아 있는 브라우저.
|
|
248
|
+
|
|
249
|
+
## 환경 변수
|
|
250
|
+
|
|
251
|
+
| 변수 | 같은 옵션 | 예 |
|
|
252
|
+
|---|---|---|
|
|
253
|
+
| `HEADLESS_REAPER_MIN_AGE` | `--min-age` | `30m` |
|
|
254
|
+
| `HEADLESS_REAPER_PATH` | `--path` | `/srv/app/_tmp:/srv/other/_tmp` |
|
|
255
|
+
| `HEADLESS_REAPER_GRACE` | `--grace` | `5s` |
|
|
256
|
+
|
|
257
|
+
명령줄 옵션이 항상 환경 변수보다 우선합니다. `HEADLESS_REAPER_PATH`는 macOS와 Linux에서 `:`로 나눕니다.
|
|
258
|
+
|
|
259
|
+
## 파이썬에서 쓰기
|
|
260
|
+
|
|
261
|
+
```python
|
|
262
|
+
import time
|
|
263
|
+
|
|
264
|
+
from headless_reaper import clean_clones, cleanup_profiles, find_groups, list_processes, reap
|
|
265
|
+
|
|
266
|
+
procs = list_processes()
|
|
267
|
+
groups = find_groups(procs, now=time.time(), min_age=600, paths=("/srv/app/_tmp",))
|
|
268
|
+
for group in groups:
|
|
269
|
+
print(group.root.pid, group.profile, group.signals, group.rss_bytes())
|
|
270
|
+
|
|
271
|
+
result = reap(groups)
|
|
272
|
+
print(result.sigterm, result.sigkill, result.survivors)
|
|
273
|
+
|
|
274
|
+
removed, kept = cleanup_profiles(groups)
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`list_processes()`는 `Proc` 레코드(`pid`, `ppid`, `rss_bytes`, `started_at`, `state`, `exe`, `argv`)를 돌려줍니다. `find_groups()`는 `root`, `members`, `profile`, `signals`, `reason`이 담긴 `Group`을 돌려주고, `pids`, `rss_bytes()`, `age_seconds(now)`를 함께 제공합니다.
|
|
278
|
+
|
|
279
|
+
## 한계
|
|
280
|
+
|
|
281
|
+
시험한 환경:
|
|
282
|
+
|
|
283
|
+
- macOS 27, arm64, Google Chrome 157. 짧게 살다 끝나는 부모에서 헤드리스 크롬을 띄워 일부러 방치한 경우와, 부모가 살아 있는 채로 띄운 경우를 각각 만들었습니다. 첫 번째는 찾아서 정리했고, 두 번째는 그대로 두었으며, 이 머신에서 평소 쓰는 크롬 창은 건드리지 않았습니다.
|
|
284
|
+
- Ubuntu 24.04, arm64, Playwright Chromium 헤드리스 셸 159와 Playwright Firefox 159. 엔진마다 방치 프로세스를 하나씩 만들어 찾고, 정리하고, 임시 프로필까지 지웠습니다. Playwright가 실제로 넘기는 인자(크로미움은 `--headless`, `--user-data-dir=/tmp/playwright_chromiumdev_profile-…`, `--remote-debugging-pipe`, 파이어폭스는 `-headless -profile …`)가 이 도구가 맞추는 값과 같습니다.
|
|
285
|
+
|
|
286
|
+
시험하지 않은 것:
|
|
287
|
+
|
|
288
|
+
- **Windows 브라우저 탐지.** 두 구현 모두 백엔드가 없습니다. Rust GNU x86_64 빌드와 종료 코드 2 응답까지 확인했으며, 브라우저는 조회하거나 정리하지 않습니다.
|
|
289
|
+
- **WebKit 실제 실행.** 시험한 머신의 Playwright WebKit 빌드에 GTK 4 라이브러리가 없어서, 인자 모양(`pw_run.sh --headless --user-data-dir=/tmp/playwright_webkitdev_profile-…`)만 탐지 규칙에 넣어 확인했고 실제 브라우저는 띄우지 못했습니다.
|
|
290
|
+
- **macOS/Linux x86_64.** 두 OS의 프로세스 백엔드는 x86_64에서 실행하지 않았습니다. Windows x86_64에서는 미지원 플랫폼 분기만 실행했습니다.
|
|
291
|
+
- **Python macOS `ps`와 공백.** Python 참조 구현은 `ps`의 공백 구분 출력에서 공백이 들어간 프로필 경로를 복원하지 못합니다. Rust는 `KERN_PROCARGS2`로 정확한 인자를 읽고 libproc으로 PID·부모·시작 시각·RSS를 읽습니다. Linux에서는 두 구현 모두 정확한 인자를 읽습니다. macOS에서 조회할 수 없는 PID도 목록에 유지하므로, 그 자식의 살아 있는 부모를 사라졌다고 판단하지 않습니다.
|
|
292
|
+
- **launchd나 systemd가 직접 띄운 브라우저.** 부모가 init 프로세스라서 방치된 것과 똑같이 보입니다. `--path`로 범위를 좁히거나, 재시작 주기보다 긴 `--min-age`를 주세요.
|
|
293
|
+
- **실제 프로필을 쓰는 화면 있는 자동화 브라우저.** 예를 들어 `headless: false`로 띄운 Puppeteer가 홈 디렉터리 아래 프로젝트 프로필을 쓰는 경우, 부모가 죽어도 정리하지 않습니다. 사람이 쓰고 있을 수 있는 창을 닫느니 그대로 두는 쪽을 고른 것입니다. 이런 프로필도 정리하고 싶다면 임시 경로 아래에 두세요.
|
|
294
|
+
|
|
295
|
+
## 에이전트에서 쓰기
|
|
296
|
+
|
|
297
|
+
AI 에이전트가 남은 브라우저를 정리해야 한다면 [AGENTS.md](https://github.com/elfenomenokim/headless-reaper/blob/main/AGENTS.md)를 읽으세요. Claude Code 스킬은 [`skill/headless-reaper/SKILL.md`](https://github.com/elfenomenokim/headless-reaper/blob/main/skill/headless-reaper/SKILL.md)에 있습니다. 이 폴더를 `~/.claude/skills/headless-reaper/`로 복사하면 설치됩니다.
|
|
298
|
+
|
|
299
|
+
## 라이선스
|
|
300
|
+
|
|
301
|
+
MIT입니다. [LICENSE](https://github.com/elfenomenokim/headless-reaper/blob/main/LICENSE)를 보세요.
|