pm2-rpc 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.
@@ -0,0 +1,10 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
pm2_rpc-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Soares
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.
pm2_rpc-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: pm2-rpc
3
+ Version: 0.1.0
4
+ Summary: Pure-Python client for PM2's daemon RPC socket
5
+ Project-URL: Repository, https://github.com/cadance-io/pm2-rpc
6
+ Project-URL: Issues, https://github.com/cadance-io/pm2-rpc/issues
7
+ Author: Paul Soares
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: amp,axon,pm2,process-manager,rpc
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: POSIX
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: System :: Systems Administration
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Description-Content-Type: text/markdown
21
+
22
+ # pm2-rpc
23
+
24
+ Pure-Python client for [PM2](https://pm2.keymetrics.io/)'s daemon RPC socket.
25
+
26
+ > [!CAUTION]
27
+ > **Experimental (v0.1.0)** — Early-stage personal project. The API will change without notice.
28
+
29
+ Talks directly to the `~/.pm2/rpc.sock` Unix socket using PM2's
30
+ `pm2-axon` / `pm2-axon-rpc` wire stack (AMP framing -> amp-message arg
31
+ packing -> axon-rpc body). No `pm2` CLI shell-out for the common cases.
32
+
33
+ ## Quick Start
34
+
35
+ ```python
36
+ import pm2
37
+
38
+ for p in pm2.list():
39
+ print(p.pm_id, p.name, p.status)
40
+
41
+ pm2.stop("worker")
42
+ pm2.delete("worker")
43
+ ```
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install pm2-rpc
49
+ ```
50
+
51
+ Requires Python >= 3.12 and a running PM2 daemon on the same host.
52
+
53
+ ## Development
54
+
55
+ ```bash
56
+ uv sync --group dev
57
+ uv run pytest tests/ # requires a real PM2 daemon
58
+ ```
59
+
60
+ ## License
61
+
62
+ MIT — see [`LICENSE`](LICENSE).
@@ -0,0 +1,41 @@
1
+ # pm2-rpc
2
+
3
+ Pure-Python client for [PM2](https://pm2.keymetrics.io/)'s daemon RPC socket.
4
+
5
+ > [!CAUTION]
6
+ > **Experimental (v0.1.0)** — Early-stage personal project. The API will change without notice.
7
+
8
+ Talks directly to the `~/.pm2/rpc.sock` Unix socket using PM2's
9
+ `pm2-axon` / `pm2-axon-rpc` wire stack (AMP framing -> amp-message arg
10
+ packing -> axon-rpc body). No `pm2` CLI shell-out for the common cases.
11
+
12
+ ## Quick Start
13
+
14
+ ```python
15
+ import pm2
16
+
17
+ for p in pm2.list():
18
+ print(p.pm_id, p.name, p.status)
19
+
20
+ pm2.stop("worker")
21
+ pm2.delete("worker")
22
+ ```
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install pm2-rpc
28
+ ```
29
+
30
+ Requires Python >= 3.12 and a running PM2 daemon on the same host.
31
+
32
+ ## Development
33
+
34
+ ```bash
35
+ uv sync --group dev
36
+ uv run pytest tests/ # requires a real PM2 daemon
37
+ ```
38
+
39
+ ## License
40
+
41
+ MIT — see [`LICENSE`](LICENSE).
pm2_rpc-0.1.0/axon.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ Minimal pm2-axon / pm2-axon-rpc client.
3
+
4
+ Wire stack:
5
+
6
+ AMP framing -> amp-message arg packing -> axon-rpc body
7
+
8
+ AMP framing (one frame per message):
9
+ 1 byte: (version << 4) | argc # version = 1, argc = 0..15
10
+ for each arg:
11
+ 4 bytes big-endian length
12
+ <length> bytes of arg data
13
+
14
+ amp-message arg encoding:
15
+ string -> b"s:" + utf8(s)
16
+ object -> b"j:" + utf8(json.dumps(obj))
17
+ bytes -> raw
18
+
19
+ axon-rpc REQ/REP body (arg 0 is the message; arg 1 is the REQ id echoed back):
20
+ request : {"type": "call", "method": <name>, "args": [...]}
21
+ reply : {"args": [<result>...]} or {"error": "...", "stack": "..."}
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import socket
29
+ import struct
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ SOCK_PATH = Path.home() / ".pm2" / "rpc.sock"
34
+ AMP_VERSION = 1
35
+
36
+
37
+ class PM2Error(RuntimeError):
38
+ """Raised when the daemon returns an error reply."""
39
+
40
+
41
+ def _recv_exact(sock: socket.socket, n: int) -> bytes:
42
+ buf = bytearray()
43
+ while len(buf) < n:
44
+ chunk = sock.recv(n - len(buf))
45
+ if not chunk:
46
+ raise ConnectionError("PM2 daemon closed the socket mid-frame")
47
+ buf.extend(chunk)
48
+ return bytes(buf)
49
+
50
+
51
+ def _pack_arg(value: Any) -> bytes:
52
+ if isinstance(value, (bytes, bytearray)):
53
+ return bytes(value)
54
+ if isinstance(value, str):
55
+ return b"s:" + value.encode("utf-8")
56
+ return b"j:" + json.dumps(value, separators=(",", ":")).encode("utf-8")
57
+
58
+
59
+ def _unpack_arg(raw: bytes) -> Any:
60
+ if raw[:2] == b"j:":
61
+ return json.loads(raw[2:].decode("utf-8"))
62
+ if raw[:2] == b"s:":
63
+ return raw[2:].decode("utf-8")
64
+ return raw
65
+
66
+
67
+ def _encode_amp(args: list[Any]) -> bytes:
68
+ if not 0 <= len(args) <= 0xF:
69
+ raise ValueError("AMP supports at most 15 args per message")
70
+ packed = [_pack_arg(a) for a in args]
71
+ out = bytearray()
72
+ out.append((AMP_VERSION << 4) | len(packed))
73
+ for p in packed:
74
+ out.extend(struct.pack(">I", len(p)))
75
+ out.extend(p)
76
+ return bytes(out)
77
+
78
+
79
+ def _read_amp(sock: socket.socket) -> list[Any]:
80
+ meta = _recv_exact(sock, 1)[0]
81
+ version = meta >> 4
82
+ argc = meta & 0x0F
83
+ if version != AMP_VERSION:
84
+ raise ValueError(f"unsupported AMP version {version}")
85
+ args = []
86
+ for _ in range(argc):
87
+ (length,) = struct.unpack(">I", _recv_exact(sock, 4))
88
+ args.append(_unpack_arg(_recv_exact(sock, length)))
89
+ return args
90
+
91
+
92
+ def rpc_call(method: str, *args: Any, timeout: float = 10.0) -> Any:
93
+ """Make one axon-rpc call against PM2's daemon and return its result list."""
94
+ req_id = f"{os.getpid()}:0"
95
+ body = {"type": "call", "method": method, "args": list(args)}
96
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
97
+ s.settimeout(timeout)
98
+ s.connect(str(SOCK_PATH))
99
+ s.sendall(_encode_amp([body, req_id]))
100
+ reply_args = _read_amp(s)
101
+
102
+ if len(reply_args) < 2:
103
+ raise PM2Error(f"unexpected reply shape: {reply_args!r}")
104
+ msg, echoed_id = reply_args[0], reply_args[1]
105
+ if echoed_id != req_id:
106
+ raise PM2Error(f"id mismatch: sent {req_id!r}, got {echoed_id!r}")
107
+ if isinstance(msg, dict) and "error" in msg:
108
+ raise PM2Error(f"{msg['error']}\n{msg.get('stack', '')}".rstrip())
109
+ if isinstance(msg, dict) and "args" in msg:
110
+ return msg["args"]
111
+ return msg
112
+
113
+
114
+ def list_methods() -> dict:
115
+ """Ask the daemon what methods it exposes (uses the {type:'methods'} body)."""
116
+ req_id = f"{os.getpid()}:0"
117
+ body = {"type": "methods"}
118
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
119
+ s.settimeout(5.0)
120
+ s.connect(str(SOCK_PATH))
121
+ s.sendall(_encode_amp([body, req_id]))
122
+ reply_args = _read_amp(s)
123
+ return reply_args[0].get("methods", {})
pm2_rpc-0.1.0/pm2.py ADDED
@@ -0,0 +1,211 @@
1
+ """Pythonic API over PM2's RPC socket. Mirrors a subset of the `pm2` CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import axon
12
+
13
+
14
+ class NotFound(LookupError):
15
+ """Raised when a target name or id isn't registered with PM2."""
16
+
17
+
18
+ class Process:
19
+ """Thin view over one PM2 process snapshot. Wraps the dict shape returned
20
+ by the daemon's `getMonitorData` so callers can use attribute access."""
21
+
22
+ __slots__ = ("_raw",)
23
+
24
+ def __init__(self, raw: dict) -> None:
25
+ self._raw = raw
26
+
27
+ @property
28
+ def raw(self) -> dict:
29
+ return self._raw
30
+
31
+ @property
32
+ def pm2_env(self) -> dict:
33
+ return self._raw.get("pm2_env", {})
34
+
35
+ @property
36
+ def pm_id(self) -> int:
37
+ return self.pm2_env.get("pm_id", self._raw.get("pm_id"))
38
+
39
+ @property
40
+ def name(self) -> str:
41
+ return self.pm2_env.get("name") or self._raw.get("name", "")
42
+
43
+ @property
44
+ def pid(self) -> int | None:
45
+ v = self._raw.get("pid")
46
+ return v if v else None
47
+
48
+ @property
49
+ def status(self) -> str:
50
+ return self.pm2_env.get("status", "")
51
+
52
+ @property
53
+ def restart_time(self) -> int:
54
+ return self.pm2_env.get("restart_time", 0)
55
+
56
+ def __repr__(self) -> str:
57
+ return f"<Process pm_id={self.pm_id} name={self.name!r} status={self.status!r}>"
58
+
59
+
60
+ def list() -> "builtins.list[Process]": # type: ignore[name-defined]
61
+ """Return every process currently managed by the PM2 daemon."""
62
+ (raw,) = axon.rpc_call("getMonitorData", {})
63
+ return [Process(p) for p in raw]
64
+
65
+
66
+ def exists(name: str) -> bool:
67
+ """True iff a process with that name is registered (any status)."""
68
+ return any(p.name == name for p in list())
69
+
70
+
71
+ def _find(target: str | int, procs: "builtins.list[Process]") -> Process | None: # type: ignore[name-defined]
72
+ if isinstance(target, int):
73
+ return next((p for p in procs if p.pm_id == target), None)
74
+ return next((p for p in procs if p.name == target), None)
75
+
76
+
77
+ def describe(target: str | int) -> Process:
78
+ """Return the Process for `target` (name or pm_id).
79
+
80
+ Mirrors `pm2 describe <name>` — raises NotFound if unregistered, so
81
+ callers can use a try/except as an existence probe.
82
+ """
83
+ found = _find(target, list())
84
+ if found is None:
85
+ raise NotFound(f"no PM2 process matches {target!r}")
86
+ return found
87
+
88
+
89
+ def restart(
90
+ target: str | int,
91
+ *,
92
+ env: dict[str, str] | None = None,
93
+ update_env: bool = False,
94
+ ) -> Process:
95
+ """Restart a process. Mirrors `pm2 restart <name>` with optional env-merge.
96
+
97
+ Args:
98
+ target: process name or pm_id
99
+ env: extra env vars to merge into the process's pm2_env.env
100
+ update_env: when True, current `os.environ` is merged too — mirrors
101
+ `pm2 restart NAME --update-env`. If both are given, `env` takes
102
+ precedence (it's merged last).
103
+
104
+ The daemon's restartProcessId accepts `{id, env}` and `Object.assign`s
105
+ env into the existing process env, so this is one round-trip.
106
+ """
107
+ proc = describe(target)
108
+ merged: dict[str, str] = {}
109
+ if update_env:
110
+ merged.update(os.environ)
111
+ if env:
112
+ merged.update(env)
113
+ opts: dict[str, Any] = {"id": proc.pm_id}
114
+ if merged:
115
+ opts["env"] = merged
116
+ axon.rpc_call("restartProcessId", opts)
117
+ return describe(proc.pm_id)
118
+
119
+
120
+ def stop(target: str | int) -> Process:
121
+ """Gracefully stop a process. Keeps the entry registered with PM2
122
+ (status='stopped'), mirroring `pm2 stop <name>`."""
123
+ proc = describe(target)
124
+ axon.rpc_call("stopProcessId", proc.pm_id)
125
+ return describe(proc.pm_id)
126
+
127
+
128
+ def delete(target: str | int) -> None:
129
+ """Remove a process entry entirely, like `pm2 delete <name>`."""
130
+ proc = describe(target)
131
+ axon.rpc_call("deleteProcessId", proc.pm_id)
132
+
133
+
134
+ def env(target: str | int) -> dict[str, str]:
135
+ """The merged env dict the running process actually sees.
136
+
137
+ Mirrors `pm2 env <id>` (which prints the same thing line-by-line). Use
138
+ this to short-circuit work like 'already in suite mode, skip restart'.
139
+ """
140
+ return dict(describe(target).pm2_env.get("env", {}))
141
+
142
+
143
+ def logs(target: str | int, lines: int = 15, *, stream: str = "out") -> str:
144
+ """Return the last `lines` lines of the process log.
145
+
146
+ Mirrors `pm2 logs <name> --lines N --nostream`. PM2 keeps the log file
147
+ path on disk in pm2_env.pm_out_log_path / pm_err_log_path — we read it
148
+ directly rather than going through the daemon.
149
+
150
+ Args:
151
+ target: name or pm_id
152
+ lines: how many trailing lines to return
153
+ stream: 'out' (stdout) or 'err' (stderr)
154
+ """
155
+ if stream not in ("out", "err"):
156
+ raise ValueError(f"stream must be 'out' or 'err', got {stream!r}")
157
+ proc = describe(target)
158
+ path = proc.pm2_env.get(f"pm_{stream}_log_path")
159
+ if not path or not os.path.exists(path):
160
+ return ""
161
+ with open(path, encoding="utf-8", errors="replace") as f:
162
+ all_lines = f.read().splitlines()
163
+ return "\n".join(all_lines[-lines:])
164
+
165
+
166
+ def start_ecosystem(
167
+ config: str | Path,
168
+ *,
169
+ only: str | None = None,
170
+ cwd: str | Path | None = None,
171
+ ) -> "builtins.list[Process]": # type: ignore[name-defined]
172
+ """Bootstrap one or more apps from an `ecosystem.config.js` file.
173
+
174
+ Delegates to the `pm2 start` CLI because evaluating a `.js` config
175
+ requires the node runtime — pure RPC can't do it. The CLI parses the
176
+ file, builds the app config, then sends `prepare` over the same RPC
177
+ socket we use everywhere else.
178
+
179
+ Args:
180
+ config: path to ecosystem.config.{js,cjs,json}
181
+ only: when set, start only the named app — sibling apps in the
182
+ file are untouched, matching `pm2 start --only NAME`
183
+ cwd: working directory; defaults to where Python is running
184
+
185
+ Returns: Process snapshots for whatever was started (filtered to `only`
186
+ when given).
187
+ """
188
+ pm2_bin = shutil.which("pm2")
189
+ if pm2_bin is None:
190
+ raise RuntimeError("pm2 CLI not on PATH — needed to parse .js configs")
191
+
192
+ cmd = [pm2_bin, "start", str(config)]
193
+ if only is not None:
194
+ cmd.extend(["--only", only])
195
+
196
+ result = subprocess.run(
197
+ cmd,
198
+ cwd=str(cwd) if cwd is not None else None,
199
+ capture_output=True,
200
+ text=True,
201
+ )
202
+ if result.returncode != 0:
203
+ raise RuntimeError(
204
+ f"pm2 start failed (exit {result.returncode}):\n"
205
+ f"stdout: {result.stdout}\nstderr: {result.stderr}"
206
+ )
207
+
208
+ all_procs = list()
209
+ if only is not None:
210
+ return [p for p in all_procs if p.name == only]
211
+ return all_procs
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pm2-rpc"
7
+ version = "0.1.0"
8
+ description = "Pure-Python client for PM2's daemon RPC socket"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ authors = [{name = "Paul Soares"}]
13
+ keywords = ["pm2", "rpc", "axon", "amp", "process-manager"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Operating System :: POSIX",
21
+ "Topic :: System :: Systems Administration",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.urls]
27
+ Repository = "https://github.com/cadance-io/pm2-rpc"
28
+ Issues = "https://github.com/cadance-io/pm2-rpc/issues"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "pytest>=9.0.3",
33
+ ]
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ # Flat layout: ship the two top-level modules as the public surface.
37
+ # `main.py` is a demo entry point and intentionally excluded.
38
+ only-include = ["pm2.py", "axon.py"]
39
+ sources = ["."]
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ only-include = ["pm2.py", "axon.py", "README.md", "LICENSE", "pyproject.toml"]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]