wpcc 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +155 -2
- package/bin/wpcc.js +7 -0
- package/package.json +41 -4
- package/src/cache.js +85 -0
- package/src/format.js +33 -0
- package/src/index.js +92 -0
- package/src/meminfo.js +70 -0
- package/src/tui.js +310 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wpcc contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,156 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wpcc — Watch & Purge Cache
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An **ultra-lightweight, htop-style memory monitor for Linux** that safely clears reclaimable kernel caches when it starts and shows you exactly how much memory was freed.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
wpcc v1.0.0 Watch & Purge Cache my-laptop up 6h 33m load 1.43 1.33 1.31 17:16:24
|
|
7
|
+
|
|
8
|
+
Mem [||||||||||||||||||||||||||||||||||||||||||||||||| ] 70.3% 10.9 GB / 15.5 GB
|
|
9
|
+
Avail [||||||||||||| ] 22.1% 3.4 GB available
|
|
10
|
+
Cache [|||||||||||||||| ] 27.4% 4.3 GB reclaimable
|
|
11
|
+
Swap [|| ] 3.6% 74.1 MB / 2.0 GB
|
|
12
|
+
| used | buffers | cache
|
|
13
|
+
|
|
14
|
+
Total 15.5 GB Buffers 312.8 MB
|
|
15
|
+
Used 10.9 GB Cached 3.6 GB
|
|
16
|
+
Free 350.3 MB SReclaimable 379.7 MB
|
|
17
|
+
Available 3.4 GB Shmem 872.3 MB
|
|
18
|
+
Swap used 74.1 MB Dirty 1.5 MB
|
|
19
|
+
|
|
20
|
+
Cache clear
|
|
21
|
+
✔ Freed: 3.4 GB cache 4.3 GB → 0.9 GB · 212 ms · at 17:16:23
|
|
22
|
+
Session: 1 clear(s), 3.4 GB freed in total
|
|
23
|
+
|
|
24
|
+
c Clear r Refresh q Quit ● root: cache clearing enabled
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- **Zero dependencies.** Plain Node.js and ANSI escape codes, so it installs in seconds and uses very little CPU and memory.
|
|
28
|
+
- **Live view** of total, used, available, reclaimable cache and swap, read from `/proc/meminfo`.
|
|
29
|
+
- **Clears cache on launch** (`sync` followed by `echo 3 > /proc/sys/vm/drop_caches`) and reports the memory freed.
|
|
30
|
+
- **Fails safely without root.** The UI keeps running and tells you to use `sudo`.
|
|
31
|
+
|
|
32
|
+
## Requirements
|
|
33
|
+
|
|
34
|
+
- Linux (Ubuntu, Debian, Fedora, Arch, and so on). On macOS and Windows, wpcc prints a clear message and exits.
|
|
35
|
+
- Node.js 14 or newer.
|
|
36
|
+
- Root (`sudo`) **only** for clearing caches. Monitoring works for any user.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install -g wpcc
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Or run it once without installing:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx wpcc --no-clear
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
sudo wpcc # clear caches now, then watch memory live
|
|
54
|
+
wpcc # watch memory only (clearing needs root, and the UI tells you so)
|
|
55
|
+
wpcc --no-clear # watch only, without clearing on launch
|
|
56
|
+
wpcc --once # print one snapshot and exit (useful in scripts)
|
|
57
|
+
wpcc -i 2 # refresh every 2 seconds
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
| Option | Description |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `--no-clear` | Don't clear caches on launch |
|
|
63
|
+
| `-i, --interval <sec>` | Refresh interval in seconds (default `1`, minimum `0.2`) |
|
|
64
|
+
| `--once` | Print a single snapshot and exit. This is also used automatically when output is piped. |
|
|
65
|
+
| `--no-color` | Disable colors. The `NO_COLOR` environment variable is also honored. |
|
|
66
|
+
| `-h, --help` | Show help |
|
|
67
|
+
| `-v, --version` | Show version |
|
|
68
|
+
|
|
69
|
+
**Keyboard shortcuts in the live UI**
|
|
70
|
+
|
|
71
|
+
| Key | Action |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `c` | Clear caches again and update the "Freed" readout |
|
|
74
|
+
| `r` | Refresh now |
|
|
75
|
+
| `q` / `Ctrl+C` | Quit and restore the terminal |
|
|
76
|
+
|
|
77
|
+
### "sudo: wpcc: command not found"?
|
|
78
|
+
|
|
79
|
+
If you installed Node with **nvm** (or another per-user manager), `sudo` uses a different `PATH` and cannot find `node` or `wpcc`. Keep your `PATH` when calling sudo:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
sudo env "PATH=$PATH" wpcc
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## How cache clearing works (and why it's safe)
|
|
86
|
+
|
|
87
|
+
Linux uses spare RAM to cache files you've read (the **page cache**) and filesystem metadata (**dentries** and **inodes**). This is a good thing: cached data is served from RAM instead of disk, and the kernel frees it automatically when programs need memory. That's why `Available` is much larger than `Free`.
|
|
88
|
+
|
|
89
|
+
When you run wpcc as root, it:
|
|
90
|
+
|
|
91
|
+
1. **Runs `sync`.** This writes all pending ("dirty") data to disk, so nothing that hasn't been saved yet is involved.
|
|
92
|
+
2. **Writes `3` to `/proc/sys/vm/drop_caches`.** The kernel then discards *clean* cached pages, dentries and inodes:
|
|
93
|
+
- `1` = page cache only
|
|
94
|
+
- `2` = dentries + inodes
|
|
95
|
+
- `3` = both
|
|
96
|
+
3. **Reads `/proc/meminfo` before and after**, and shows how much memory moved from cache back to free (`Freed: …`).
|
|
97
|
+
|
|
98
|
+
This is **non-destructive**. The kernel never drops dirty pages or memory that belongs to running programs. Nothing is lost; the cache simply refills as files are read again.
|
|
99
|
+
|
|
100
|
+
> **Good to know:** dropping caches does not make a system faster in normal use. Right afterwards, reading files may be slightly slower because data has to come from disk again. It's useful for benchmarking, for testing cold-cache behaviour, for seeing how much RAM your programs really use, or when you just want to see a clean baseline.
|
|
101
|
+
|
|
102
|
+
**What the numbers mean**
|
|
103
|
+
|
|
104
|
+
| Metric | Source (`/proc/meminfo`) |
|
|
105
|
+
|---|---|
|
|
106
|
+
| Total | `MemTotal` |
|
|
107
|
+
| Used | `MemTotal − MemFree − Buffers − Cached − SReclaimable` (the same convention as `htop` and `free`) |
|
|
108
|
+
| Available | `MemAvailable`: what programs can actually get, including reclaimable cache |
|
|
109
|
+
| Reclaimable cache | `Buffers + Cached + SReclaimable` |
|
|
110
|
+
| Freed | Increase in `MemFree` across the clear |
|
|
111
|
+
|
|
112
|
+
## Project structure
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
wpcc/
|
|
116
|
+
├── bin/wpcc.js # CLI entry point (#!/usr/bin/env node)
|
|
117
|
+
├── src/
|
|
118
|
+
│ ├── index.js # argument parsing, platform check, mode selection
|
|
119
|
+
│ ├── tui.js # live terminal UI (rendering, keys, terminal restore)
|
|
120
|
+
│ ├── meminfo.js # /proc/meminfo parsing and metrics
|
|
121
|
+
│ ├── cache.js # safe sync + drop_caches with permission handling
|
|
122
|
+
│ └── format.js # byte, percent and time formatting
|
|
123
|
+
├── test/run.js # dependency-free tests (npm test)
|
|
124
|
+
├── package.json
|
|
125
|
+
├── LICENSE # MIT
|
|
126
|
+
└── README.md
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Contributing
|
|
130
|
+
|
|
131
|
+
Contributions are welcome, whether you're fixing a typo or adding a feature.
|
|
132
|
+
|
|
133
|
+
1. **Fork** the repo and create a branch: `git checkout -b feature/my-idea`
|
|
134
|
+
2. **Install and run locally:**
|
|
135
|
+
```bash
|
|
136
|
+
git clone https://github.com/mahamudcu/wpcc.git
|
|
137
|
+
cd wpcc
|
|
138
|
+
npm link # makes the `wpcc` command point at your local copy
|
|
139
|
+
wpcc --no-clear
|
|
140
|
+
```
|
|
141
|
+
3. **Test:** `npm test`
|
|
142
|
+
4. **Commit** with a clear message and **open a pull request** that describes what you changed and why.
|
|
143
|
+
|
|
144
|
+
**Guidelines**
|
|
145
|
+
|
|
146
|
+
- Keep it **dependency-free** and lightweight. That's the point of the project.
|
|
147
|
+
- Never throw from the render loop. Errors should appear in the UI, and the terminal must always be restored.
|
|
148
|
+
- Keep Node 14 compatibility (avoid newer-only syntax and APIs).
|
|
149
|
+
- Add or update tests in `test/run.js` for logic changes.
|
|
150
|
+
- Be kind and constructive in issues and reviews.
|
|
151
|
+
|
|
152
|
+
**Ideas for contributions:** per-process memory top list, a `--level 1|2|3` option for drop_caches, a sparkline of memory history, a JSON output mode.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
[MIT](LICENSE)
|
package/bin/wpcc.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wpcc",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Watch & Purge Cache — an ultra-lightweight htop-style Linux memory monitor that safely drops kernel caches and shows how much memory was freed.",
|
|
5
|
+
"bin": {
|
|
6
|
+
"wpcc": "bin/wpcc.js"
|
|
7
|
+
},
|
|
8
|
+
"main": "./src/index.js",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/mahamudcu/wpcc.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/mahamudcu/wpcc#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/mahamudcu/wpcc/issues"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin/",
|
|
19
|
+
"src/",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"start": "node ./bin/wpcc.js",
|
|
25
|
+
"test": "node ./test/run.js"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=14"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"linux",
|
|
32
|
+
"memory",
|
|
33
|
+
"cache",
|
|
34
|
+
"drop_caches",
|
|
35
|
+
"pagecache",
|
|
36
|
+
"htop",
|
|
37
|
+
"tui",
|
|
38
|
+
"cli",
|
|
39
|
+
"monitor",
|
|
40
|
+
"ram"
|
|
41
|
+
],
|
|
42
|
+
"license": "MIT"
|
|
43
|
+
}
|
package/src/cache.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const { spawnSync } = require('child_process');
|
|
5
|
+
const { readMemory } = require('./meminfo');
|
|
6
|
+
|
|
7
|
+
const DROP_CACHES_PATH = '/proc/sys/vm/drop_caches';
|
|
8
|
+
|
|
9
|
+
function isRoot() {
|
|
10
|
+
return typeof process.getuid === 'function' && process.getuid() === 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** True when the current process may write to /proc/sys/vm/drop_caches. */
|
|
14
|
+
function canDropCaches() {
|
|
15
|
+
try {
|
|
16
|
+
fs.accessSync(DROP_CACHES_PATH, fs.constants.W_OK);
|
|
17
|
+
return true;
|
|
18
|
+
} catch (_) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function permissionResult(before, message) {
|
|
24
|
+
return {
|
|
25
|
+
ok: false,
|
|
26
|
+
reason: 'permission',
|
|
27
|
+
message: message || 'Permission denied — run with sudo for cache clearing (sudo wpcc)',
|
|
28
|
+
before,
|
|
29
|
+
at: new Date(),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Safely drop clean kernel caches:
|
|
35
|
+
* 1. `sync` flushes dirty pages to disk, so nothing unwritten is discarded.
|
|
36
|
+
* 2. Writing "3" to drop_caches frees the page cache, dentries and inodes.
|
|
37
|
+
* The kernel only discards *clean*, reclaimable memory; no process data is lost.
|
|
38
|
+
*
|
|
39
|
+
* Never throws: always returns a result object for the UI to display.
|
|
40
|
+
*/
|
|
41
|
+
function dropCaches() {
|
|
42
|
+
const started = Date.now();
|
|
43
|
+
let before;
|
|
44
|
+
try {
|
|
45
|
+
before = readMemory();
|
|
46
|
+
} catch (err) {
|
|
47
|
+
return { ok: false, reason: 'error', message: `Cannot read /proc/meminfo: ${err.message}`, at: new Date() };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (!canDropCaches()) return permissionResult(before);
|
|
51
|
+
|
|
52
|
+
// If sync fails we still continue: the kernel never discards dirty pages,
|
|
53
|
+
// so dropping caches stays safe — just fewer pages are reclaimable.
|
|
54
|
+
const sync = spawnSync('sync', { stdio: 'ignore', timeout: 60000 });
|
|
55
|
+
const synced = !sync.error && sync.status === 0;
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
fs.writeFileSync(DROP_CACHES_PATH, '3\n');
|
|
59
|
+
} catch (err) {
|
|
60
|
+
if (err.code === 'EACCES' || err.code === 'EPERM' || err.code === 'EROFS') {
|
|
61
|
+
return permissionResult(
|
|
62
|
+
before,
|
|
63
|
+
err.code === 'EROFS'
|
|
64
|
+
? 'drop_caches is read-only here (container/VM?) — cannot clear cache'
|
|
65
|
+
: undefined
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return { ok: false, reason: 'error', message: `Cache clear failed: ${err.message}`, before, at: new Date() };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const after = readMemory();
|
|
72
|
+
return {
|
|
73
|
+
ok: true,
|
|
74
|
+
before,
|
|
75
|
+
after,
|
|
76
|
+
// Memory that moved from "cache" back to "free".
|
|
77
|
+
freed: Math.max(0, after.free - before.free),
|
|
78
|
+
cacheDropped: Math.max(0, before.cache - after.cache),
|
|
79
|
+
synced,
|
|
80
|
+
durationMs: Date.now() - started,
|
|
81
|
+
at: new Date(),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = { dropCaches, canDropCaches, isRoot, DROP_CACHES_PATH };
|
package/src/format.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
4
|
+
|
|
5
|
+
/** Human-readable size using 1024-based units (matches free/htop). */
|
|
6
|
+
function formatBytes(bytes, decimals = 1) {
|
|
7
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
|
8
|
+
let i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), UNITS.length - 1);
|
|
9
|
+
const value = bytes / Math.pow(1024, i);
|
|
10
|
+
return `${value.toFixed(i === 0 ? 0 : decimals)} ${UNITS[i]}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function formatPercent(part, whole) {
|
|
14
|
+
if (!whole) return '0.0%';
|
|
15
|
+
return `${((part / whole) * 100).toFixed(1)}%`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function formatDuration(seconds) {
|
|
19
|
+
seconds = Math.floor(seconds);
|
|
20
|
+
const d = Math.floor(seconds / 86400);
|
|
21
|
+
const h = Math.floor((seconds % 86400) / 3600);
|
|
22
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
23
|
+
if (d > 0) return `${d}d ${h}h ${m}m`;
|
|
24
|
+
if (h > 0) return `${h}h ${m}m`;
|
|
25
|
+
return `${m}m ${seconds % 60}s`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatTime(date) {
|
|
29
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
30
|
+
return `${p(date.getHours())}:${p(date.getMinutes())}:${p(date.getSeconds())}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { formatBytes, formatPercent, formatDuration, formatTime };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { version } = require('../package.json');
|
|
4
|
+
|
|
5
|
+
const HELP = `wpcc v${version} — Watch & Purge Cache
|
|
6
|
+
|
|
7
|
+
A lightweight htop-style Linux memory monitor. On launch it safely drops
|
|
8
|
+
reclaimable kernel caches (sync + /proc/sys/vm/drop_caches) and shows how
|
|
9
|
+
much memory was freed, then keeps a live view of RAM, cache and swap.
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
wpcc [options]
|
|
13
|
+
sudo wpcc (root is required to clear caches)
|
|
14
|
+
|
|
15
|
+
Options:
|
|
16
|
+
--no-clear Start without clearing caches (monitor only)
|
|
17
|
+
-i, --interval <sec> Refresh interval in seconds (default: 1, min: 0.2)
|
|
18
|
+
--once Print a single snapshot and exit (no live UI)
|
|
19
|
+
--no-color Disable colors (NO_COLOR is also honored)
|
|
20
|
+
-h, --help Show this help
|
|
21
|
+
-v, --version Show version
|
|
22
|
+
|
|
23
|
+
Keys (live UI):
|
|
24
|
+
c Clear caches again r Refresh now q / Ctrl+C Quit
|
|
25
|
+
`;
|
|
26
|
+
|
|
27
|
+
function parseArgs(argv) {
|
|
28
|
+
const opts = {
|
|
29
|
+
noClear: false,
|
|
30
|
+
interval: 1000,
|
|
31
|
+
once: false,
|
|
32
|
+
color: !('NO_COLOR' in process.env),
|
|
33
|
+
help: false,
|
|
34
|
+
version: false,
|
|
35
|
+
};
|
|
36
|
+
for (let i = 0; i < argv.length; i++) {
|
|
37
|
+
let arg = argv[i];
|
|
38
|
+
let value;
|
|
39
|
+
const eq = arg.indexOf('=');
|
|
40
|
+
if (arg.startsWith('--') && eq !== -1) {
|
|
41
|
+
value = arg.slice(eq + 1);
|
|
42
|
+
arg = arg.slice(0, eq);
|
|
43
|
+
}
|
|
44
|
+
switch (arg) {
|
|
45
|
+
case '-h': case '--help': opts.help = true; break;
|
|
46
|
+
case '-v': case '-V': case '--version': opts.version = true; break;
|
|
47
|
+
case '--no-clear': opts.noClear = true; break;
|
|
48
|
+
case '--once': opts.once = true; break;
|
|
49
|
+
case '--no-color': opts.color = false; break;
|
|
50
|
+
case '-i': case '--interval': {
|
|
51
|
+
if (value === undefined) value = argv[++i];
|
|
52
|
+
const sec = Number(value);
|
|
53
|
+
if (!Number.isFinite(sec) || sec < 0.2) {
|
|
54
|
+
throw new Error(`invalid --interval "${value}" (expected a number of seconds >= 0.2)`);
|
|
55
|
+
}
|
|
56
|
+
opts.interval = Math.round(sec * 1000);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
default:
|
|
60
|
+
throw new Error(`unknown option "${argv[i]}"`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return opts;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function main(argv) {
|
|
67
|
+
let opts;
|
|
68
|
+
try {
|
|
69
|
+
opts = parseArgs(argv);
|
|
70
|
+
} catch (err) {
|
|
71
|
+
process.stderr.write(`wpcc: ${err.message}\nRun "wpcc --help" for usage.\n`);
|
|
72
|
+
return 2;
|
|
73
|
+
}
|
|
74
|
+
if (opts.help) { process.stdout.write(HELP); return 0; }
|
|
75
|
+
if (opts.version) { process.stdout.write(`${version}\n`); return 0; }
|
|
76
|
+
|
|
77
|
+
if (process.platform !== 'linux') {
|
|
78
|
+
process.stderr.write(
|
|
79
|
+
`wpcc: this tool only works on Linux (detected "${process.platform}").\n` +
|
|
80
|
+
'It reads /proc/meminfo and uses /proc/sys/vm/drop_caches, which only exist on Linux.\n'
|
|
81
|
+
);
|
|
82
|
+
return 1;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const { runInteractive, runOnce } = require('./tui');
|
|
86
|
+
const interactive = !opts.once && process.stdout.isTTY && process.stdin.isTTY;
|
|
87
|
+
if (!interactive) return runOnce(opts);
|
|
88
|
+
runInteractive(opts);
|
|
89
|
+
return null; // keep running; the TUI exits the process itself
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { main, parseArgs, HELP };
|
package/src/meminfo.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
|
|
5
|
+
const MEMINFO_PATH = '/proc/meminfo';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Parse the text of /proc/meminfo into an object of byte values.
|
|
9
|
+
* Lines look like: "MemTotal: 16314880 kB"
|
|
10
|
+
*/
|
|
11
|
+
function parseMeminfo(text) {
|
|
12
|
+
const out = {};
|
|
13
|
+
for (const line of text.split('\n')) {
|
|
14
|
+
const m = /^([\w()]+):\s+(\d+)(\s+kB)?/.exec(line);
|
|
15
|
+
if (!m) continue;
|
|
16
|
+
const n = Number(m[2]);
|
|
17
|
+
out[m[1]] = m[3] ? n * 1024 : n;
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Turn raw meminfo values into the metrics wpcc displays.
|
|
24
|
+
* "used" follows the htop/free convention: total - free - buffers - cache.
|
|
25
|
+
*/
|
|
26
|
+
function summarize(raw) {
|
|
27
|
+
const total = raw.MemTotal || 0;
|
|
28
|
+
const free = raw.MemFree || 0;
|
|
29
|
+
const buffers = raw.Buffers || 0;
|
|
30
|
+
const cached = raw.Cached || 0;
|
|
31
|
+
const sreclaimable = raw.SReclaimable || 0;
|
|
32
|
+
const shmem = raw.Shmem || 0;
|
|
33
|
+
const cache = buffers + cached + sreclaimable;
|
|
34
|
+
// MemAvailable exists on kernels >= 3.14; estimate on older ones.
|
|
35
|
+
const available = raw.MemAvailable != null ? raw.MemAvailable : free + cache;
|
|
36
|
+
const used = Math.max(0, total - free - cache);
|
|
37
|
+
const swapTotal = raw.SwapTotal || 0;
|
|
38
|
+
const swapFree = raw.SwapFree || 0;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
total,
|
|
42
|
+
free,
|
|
43
|
+
used,
|
|
44
|
+
available,
|
|
45
|
+
buffers,
|
|
46
|
+
cached,
|
|
47
|
+
sreclaimable,
|
|
48
|
+
shmem,
|
|
49
|
+
cache,
|
|
50
|
+
dirty: raw.Dirty || 0,
|
|
51
|
+
swapTotal,
|
|
52
|
+
swapFree,
|
|
53
|
+
swapUsed: Math.max(0, swapTotal - swapFree),
|
|
54
|
+
swapCached: raw.SwapCached || 0,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function readMemory() {
|
|
59
|
+
return summarize(parseMeminfo(fs.readFileSync(MEMINFO_PATH, 'utf8')));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readUptime() {
|
|
63
|
+
try {
|
|
64
|
+
return Number(fs.readFileSync('/proc/uptime', 'utf8').split(' ')[0]) || 0;
|
|
65
|
+
} catch (_) {
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = { parseMeminfo, summarize, readMemory, readUptime, MEMINFO_PATH };
|
package/src/tui.js
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const { readMemory, readUptime } = require('./meminfo');
|
|
5
|
+
const { dropCaches, canDropCaches, isRoot } = require('./cache');
|
|
6
|
+
const { formatBytes, formatPercent, formatDuration, formatTime } = require('./format');
|
|
7
|
+
const { version } = require('../package.json');
|
|
8
|
+
|
|
9
|
+
const CSI = '\x1b[';
|
|
10
|
+
const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/;
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------- styling --
|
|
13
|
+
|
|
14
|
+
function makeColors(enabled) {
|
|
15
|
+
const wrap = (code) => (s) => (enabled ? `${CSI}${code}m${s}${CSI}0m` : String(s));
|
|
16
|
+
return {
|
|
17
|
+
enabled,
|
|
18
|
+
bold: wrap('1'),
|
|
19
|
+
dim: wrap('2'),
|
|
20
|
+
red: wrap('31'),
|
|
21
|
+
green: wrap('32'),
|
|
22
|
+
yellow: wrap('33'),
|
|
23
|
+
blue: wrap('34'),
|
|
24
|
+
cyan: wrap('36'),
|
|
25
|
+
inverse: wrap('7'),
|
|
26
|
+
keyHint: wrap('30;46'), // black on cyan, like htop's function bar
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function visibleLength(s) {
|
|
31
|
+
return s.replace(new RegExp(ANSI_RE.source, 'g'), '').length;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Truncate a string containing ANSI codes to `width` visible columns. */
|
|
35
|
+
function truncate(s, width) {
|
|
36
|
+
if (visibleLength(s) <= width) return s;
|
|
37
|
+
let out = '';
|
|
38
|
+
let count = 0;
|
|
39
|
+
let i = 0;
|
|
40
|
+
while (i < s.length && count < width) {
|
|
41
|
+
if (s[i] === '\x1b') {
|
|
42
|
+
const m = ANSI_RE.exec(s.slice(i));
|
|
43
|
+
if (m && m.index === 0) {
|
|
44
|
+
out += m[0];
|
|
45
|
+
i += m[0].length;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
out += s[i++];
|
|
50
|
+
count++;
|
|
51
|
+
}
|
|
52
|
+
return out + `${CSI}0m`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function padRight(s, width) {
|
|
56
|
+
return s + ' '.repeat(Math.max(0, width - visibleLength(s)));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Join a left and right part so `right` hugs the right edge. */
|
|
60
|
+
function spread(left, right, width) {
|
|
61
|
+
const gap = width - visibleLength(left) - visibleLength(right);
|
|
62
|
+
return gap >= 1 ? left + ' '.repeat(gap) + right : left;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------- widgets --
|
|
66
|
+
|
|
67
|
+
/** htop-style meter: [||||||||| ]. Segments are stacked left to right. */
|
|
68
|
+
function meter(segments, total, width, c) {
|
|
69
|
+
const inner = Math.max(4, width - 2);
|
|
70
|
+
let body = '';
|
|
71
|
+
let filled = 0;
|
|
72
|
+
for (const seg of segments) {
|
|
73
|
+
const n = total > 0 ? Math.round((seg.value / total) * inner) : 0;
|
|
74
|
+
const len = Math.max(0, Math.min(n, inner - filled));
|
|
75
|
+
body += seg.color('|'.repeat(len));
|
|
76
|
+
filled += len;
|
|
77
|
+
}
|
|
78
|
+
return c.bold('[') + body + ' '.repeat(inner - filled) + c.bold(']');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function meterRow(label, segments, value, total, detail, cols, c) {
|
|
82
|
+
const labelCol = padRight(c.cyan(c.bold(label)), 7);
|
|
83
|
+
const pct = formatPercent(value, total).padStart(6);
|
|
84
|
+
const detailCol = `${pct} ${detail}`;
|
|
85
|
+
// Fixed detail column so every meter has the same width.
|
|
86
|
+
const barWidth = Math.max(12, Math.min(70, cols - 2 - 7 - 2 - 30));
|
|
87
|
+
return ` ${labelCol}${meter(segments, total, barWidth, c)} ${detailCol}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ----------------------------------------------------------------- screen --
|
|
91
|
+
|
|
92
|
+
/** Build the visible lines (without the bottom key bar) for the current state. */
|
|
93
|
+
function buildLines(state, cols, c) {
|
|
94
|
+
const m = state.mem;
|
|
95
|
+
const lines = [];
|
|
96
|
+
|
|
97
|
+
// Header
|
|
98
|
+
const left = `${c.inverse(c.bold(' wpcc '))} ${c.bold(`v${version}`)} ${c.dim('Watch & Purge Cache')}`;
|
|
99
|
+
const load = os.loadavg().map((n) => n.toFixed(2)).join(' ');
|
|
100
|
+
const right = c.dim(`${os.hostname()} up ${formatDuration(readUptime())} load ${load} ${formatTime(new Date())} `);
|
|
101
|
+
lines.push(spread(left, right, cols));
|
|
102
|
+
lines.push('');
|
|
103
|
+
|
|
104
|
+
// Meters
|
|
105
|
+
const cacheOnly = m.cached + m.sreclaimable;
|
|
106
|
+
lines.push(
|
|
107
|
+
meterRow('Mem', [
|
|
108
|
+
{ value: m.used, color: c.green },
|
|
109
|
+
{ value: m.buffers, color: c.blue },
|
|
110
|
+
{ value: cacheOnly, color: c.yellow },
|
|
111
|
+
], m.used, m.total, `${formatBytes(m.used)} / ${formatBytes(m.total)}`, cols, c)
|
|
112
|
+
);
|
|
113
|
+
lines.push(
|
|
114
|
+
meterRow('Avail', [{ value: m.available, color: c.cyan }], m.available, m.total,
|
|
115
|
+
`${formatBytes(m.available)} available`, cols, c)
|
|
116
|
+
);
|
|
117
|
+
lines.push(
|
|
118
|
+
meterRow('Cache', [{ value: m.cache, color: c.yellow }], m.cache, m.total,
|
|
119
|
+
`${formatBytes(m.cache)} reclaimable`, cols, c)
|
|
120
|
+
);
|
|
121
|
+
if (m.swapTotal > 0) {
|
|
122
|
+
lines.push(
|
|
123
|
+
meterRow('Swap', [{ value: m.swapUsed, color: c.red }], m.swapUsed, m.swapTotal,
|
|
124
|
+
`${formatBytes(m.swapUsed)} / ${formatBytes(m.swapTotal)}`, cols, c)
|
|
125
|
+
);
|
|
126
|
+
} else {
|
|
127
|
+
lines.push(` ${padRight(c.cyan(c.bold('Swap')), 7)}${c.dim('disabled')}`);
|
|
128
|
+
}
|
|
129
|
+
lines.push(` ${c.green('|')}${c.dim(' used ')}${c.blue('|')}${c.dim(' buffers ')}${c.yellow('|')}${c.dim(' cache')}`);
|
|
130
|
+
lines.push('');
|
|
131
|
+
|
|
132
|
+
// Details table (two columns)
|
|
133
|
+
const cell = (k, v) => padRight(` ${c.dim(k.padEnd(13))}${c.bold(v.padStart(10))}`, 30);
|
|
134
|
+
const rows = [
|
|
135
|
+
['Total', m.total, 'Buffers', m.buffers],
|
|
136
|
+
['Used', m.used, 'Cached', m.cached],
|
|
137
|
+
['Free', m.free, 'SReclaimable', m.sreclaimable],
|
|
138
|
+
['Available', m.available, 'Shmem', m.shmem],
|
|
139
|
+
['Swap used', m.swapUsed, 'Dirty', m.dirty],
|
|
140
|
+
];
|
|
141
|
+
for (const [k1, v1, k2, v2] of rows) {
|
|
142
|
+
lines.push(cell(k1, formatBytes(v1)) + ' ' + cell(k2, formatBytes(v2)));
|
|
143
|
+
}
|
|
144
|
+
lines.push('');
|
|
145
|
+
|
|
146
|
+
// Cache-clear banner
|
|
147
|
+
lines.push(` ${c.bold('Cache clear')}`);
|
|
148
|
+
lines.push(...clearBanner(state, c));
|
|
149
|
+
return lines;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function clearBanner(state, c) {
|
|
153
|
+
const r = state.lastClear;
|
|
154
|
+
if (state.clearing) return [` ${c.yellow('… Clearing caches (sync + drop_caches)…')}`];
|
|
155
|
+
if (!r) {
|
|
156
|
+
return [` ${c.dim(state.noClear
|
|
157
|
+
? `Not cleared on launch (--no-clear).${state.interactive ? ' Press c to clear now.' : ''}`
|
|
158
|
+
: 'Press c to clear reclaimable caches.')}`];
|
|
159
|
+
}
|
|
160
|
+
if (r.ok) {
|
|
161
|
+
return [
|
|
162
|
+
` ${c.green(c.bold(`✔ Freed: ${formatBytes(r.freed)}`))} ` +
|
|
163
|
+
c.dim(`cache ${formatBytes(r.before.cache)} → ${formatBytes(r.after.cache)} · ${r.durationMs} ms · at ${formatTime(r.at)}`),
|
|
164
|
+
` ${c.dim(`Session: ${state.clearCount} clear(s), ${formatBytes(state.totalFreed)} freed in total`)}`,
|
|
165
|
+
];
|
|
166
|
+
}
|
|
167
|
+
if (r.reason === 'permission') {
|
|
168
|
+
return [
|
|
169
|
+
` ${c.yellow(c.bold(`⚠ ${r.message}`))}`,
|
|
170
|
+
` ${c.dim('Tip: if sudo cannot find node (nvm), use: sudo env "PATH=$PATH" wpcc')}`,
|
|
171
|
+
];
|
|
172
|
+
}
|
|
173
|
+
return [` ${c.red(c.bold(`✖ ${r.message}`))} ${c.dim(`at ${formatTime(r.at)}`)}`];
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function keyBar(state, cols, c) {
|
|
177
|
+
const key = (k, label) => c.keyHint(` ${k} `) + ` ${label} `;
|
|
178
|
+
const left = key('c', 'Clear') + key('r', 'Refresh') + key('q', 'Quit');
|
|
179
|
+
const right = state.canDrop ? c.green('● root: cache clearing enabled ') : c.yellow('● Run with sudo for cache clearing ');
|
|
180
|
+
return spread(left, right, cols);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ------------------------------------------------------------------- app --
|
|
184
|
+
|
|
185
|
+
function createState(options) {
|
|
186
|
+
return {
|
|
187
|
+
mem: readMemory(),
|
|
188
|
+
lastClear: null,
|
|
189
|
+
clearing: false,
|
|
190
|
+
clearCount: 0,
|
|
191
|
+
totalFreed: 0,
|
|
192
|
+
noClear: !!options.noClear,
|
|
193
|
+
interactive: !!options.interactive,
|
|
194
|
+
canDrop: canDropCaches(),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function applyClear(state) {
|
|
199
|
+
const r = dropCaches();
|
|
200
|
+
state.lastClear = r;
|
|
201
|
+
if (r.ok) {
|
|
202
|
+
state.clearCount += 1;
|
|
203
|
+
state.totalFreed += r.freed;
|
|
204
|
+
state.mem = r.after;
|
|
205
|
+
}
|
|
206
|
+
state.canDrop = canDropCaches();
|
|
207
|
+
return r;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Non-interactive mode: print one snapshot and exit (used for --once or when piped). */
|
|
211
|
+
function runOnce(options) {
|
|
212
|
+
const c = makeColors(options.color && process.stdout.isTTY);
|
|
213
|
+
const state = createState(options);
|
|
214
|
+
if (!options.noClear) applyClear(state);
|
|
215
|
+
state.mem = readMemory();
|
|
216
|
+
const cols = process.stdout.columns || 100;
|
|
217
|
+
process.stdout.write(buildLines(state, cols, c).join('\n') + '\n');
|
|
218
|
+
return state.lastClear && !state.lastClear.ok ? 1 : 0;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Interactive live TUI. */
|
|
222
|
+
function runInteractive(options) {
|
|
223
|
+
const out = process.stdout;
|
|
224
|
+
const stdin = process.stdin;
|
|
225
|
+
const c = makeColors(options.color);
|
|
226
|
+
const state = createState({ ...options, interactive: true });
|
|
227
|
+
let timer = null;
|
|
228
|
+
let closed = false;
|
|
229
|
+
|
|
230
|
+
const render = () => {
|
|
231
|
+
if (closed) return;
|
|
232
|
+
const cols = out.columns || 80;
|
|
233
|
+
const rows = out.rows || 24;
|
|
234
|
+
const lines = buildLines(state, cols, c).slice(0, Math.max(0, rows - 1));
|
|
235
|
+
let frame = '';
|
|
236
|
+
for (let i = 0; i < lines.length; i++) {
|
|
237
|
+
frame += `${CSI}${i + 1};1H${truncate(lines[i], cols)}${CSI}K`;
|
|
238
|
+
}
|
|
239
|
+
for (let i = lines.length; i < rows - 1; i++) frame += `${CSI}${i + 1};1H${CSI}K`;
|
|
240
|
+
frame += `${CSI}${rows};1H${truncate(keyBar(state, cols, c), cols)}${CSI}K`;
|
|
241
|
+
out.write(frame);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const refresh = () => {
|
|
245
|
+
try {
|
|
246
|
+
state.mem = readMemory();
|
|
247
|
+
} catch (_) { /* keep last good reading */ }
|
|
248
|
+
render();
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const clearNow = () => {
|
|
252
|
+
if (state.clearing) return;
|
|
253
|
+
state.clearing = true;
|
|
254
|
+
render();
|
|
255
|
+
// Let the "Clearing…" frame reach the terminal before the blocking sync.
|
|
256
|
+
setTimeout(() => {
|
|
257
|
+
applyClear(state);
|
|
258
|
+
state.clearing = false;
|
|
259
|
+
refresh();
|
|
260
|
+
}, 20);
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const cleanup = () => {
|
|
264
|
+
if (closed) return;
|
|
265
|
+
closed = true;
|
|
266
|
+
clearInterval(timer);
|
|
267
|
+
out.write(`${CSI}0m${CSI}?25h${CSI}?1049l`); // reset style, show cursor, leave alt screen
|
|
268
|
+
if (stdin.isTTY) stdin.setRawMode(false);
|
|
269
|
+
stdin.pause();
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const quit = (code = 0) => {
|
|
273
|
+
cleanup();
|
|
274
|
+
if (state.clearCount > 0) {
|
|
275
|
+
out.write(`wpcc: ${state.clearCount} cache clear(s), ${formatBytes(state.totalFreed)} freed this session.\n`);
|
|
276
|
+
}
|
|
277
|
+
process.exit(code);
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
process.on('exit', cleanup);
|
|
281
|
+
['SIGINT', 'SIGTERM', 'SIGHUP'].forEach((sig) => process.on(sig, () => quit(0)));
|
|
282
|
+
process.on('uncaughtException', (err) => {
|
|
283
|
+
cleanup();
|
|
284
|
+
process.stderr.write(`wpcc: unexpected error: ${err && err.stack ? err.stack : err}\n`);
|
|
285
|
+
process.exit(1);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
// Enter alt screen, hide cursor, clear.
|
|
289
|
+
out.write(`${CSI}?1049h${CSI}?25l${CSI}2J`);
|
|
290
|
+
stdin.setRawMode(true);
|
|
291
|
+
stdin.setEncoding('utf8');
|
|
292
|
+
stdin.resume();
|
|
293
|
+
stdin.on('data', (chunk) => {
|
|
294
|
+
for (const ch of chunk) {
|
|
295
|
+
if (ch === 'q' || ch === 'Q' || ch === '\u0003' || ch === '\u0004') return quit(0);
|
|
296
|
+
if (ch === 'c' || ch === 'C') clearNow();
|
|
297
|
+
else if (ch === 'r' || ch === 'R') refresh();
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
out.on('resize', () => {
|
|
301
|
+
out.write(`${CSI}2J`);
|
|
302
|
+
render();
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
render();
|
|
306
|
+
if (!options.noClear) clearNow();
|
|
307
|
+
timer = setInterval(refresh, options.interval);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
module.exports = { runInteractive, runOnce, buildLines, truncate, visibleLength, makeColors };
|