Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.

0 downloads

dbbasic-object-primitive/process_manager.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-primitive.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Q Consolidate duplicate QUICKSTARTs on the top-level file 503f830 7 months ago History
process_manager.py · 5.1 KB · 188 lines
1#!/usr/bin/env python3
2"""
3Process Manager - PID file-based process management
4
5Best practices:
6- PID files prevent duplicate processes
7- Clean shutdown using actual process IDs
8- Automatic stale PID file cleanup
9- Process status checking
10"""
11import os
12import sys
13import signal
14import time
15from pathlib import Path
16
17
18class ProcessManager:
19 """Manage processes using PID files"""
20
21 def __init__(self, name: str, pid_dir: Path = None):
22 """
23 Initialize process manager
24
25 Args:
26 name: Process name (used for PID filename)
27 pid_dir: Directory for PID files (default: ./pids/)
28 """
29 self.name = name
30 self.pid_dir = pid_dir or Path('pids')
31 self.pid_dir.mkdir(exist_ok=True)
32 self.pid_file = self.pid_dir / f'{name}.pid'
33
34 def is_running(self) -> bool:
35 """Check if process is currently running"""
36 if not self.pid_file.exists():
37 return False
38
39 try:
40 pid = int(self.pid_file.read_text().strip())
41 # Check if process exists
42 os.kill(pid, 0) # Signal 0 doesn't kill, just checks
43 return True
44 except (ValueError, ProcessLookupError, PermissionError):
45 # PID file is stale (process doesn't exist)
46 self._cleanup_stale_pid()
47 return False
48
49 def get_pid(self) -> int | None:
50 """Get PID of running process (None if not running)"""
51 if not self.pid_file.exists():
52 return None
53
54 try:
55 pid = int(self.pid_file.read_text().strip())
56 # Verify process exists
57 os.kill(pid, 0)
58 return pid
59 except (ValueError, ProcessLookupError, PermissionError):
60 self._cleanup_stale_pid()
61 return None
62
63 def write_pid(self, pid: int = None):
64 """Write PID file for current or specified process"""
65 if pid is None:
66 pid = os.getpid()
67
68 if self.is_running():
69 existing_pid = self.get_pid()
70 raise RuntimeError(
71 f'{self.name} already running with PID {existing_pid}'
72 )
73
74 self.pid_file.write_text(str(pid))
75
76 def stop(self, timeout: int = 10) -> bool:
77 """
78 Stop process gracefully
79
80 Args:
81 timeout: Seconds to wait before force kill
82
83 Returns:
84 True if stopped successfully
85 """
86 pid = self.get_pid()
87 if pid is None:
88 print(f'{self.name} not running')
89 return True
90
91 print(f'Stopping {self.name} (PID {pid})...')
92
93 try:
94 # Try SIGTERM first (graceful shutdown)
95 os.kill(pid, signal.SIGTERM)
96
97 # Wait for process to exit
98 for i in range(timeout * 10):
99 try:
100 os.kill(pid, 0) # Check if still running
101 time.sleep(0.1)
102 except ProcessLookupError:
103 print(f'✓ {self.name} stopped')
104 self._cleanup_stale_pid()
105 return True
106
107 # Force kill if still running
108 print(f'Force killing {self.name}...')
109 os.kill(pid, signal.SIGKILL)
110 time.sleep(0.5)
111 self._cleanup_stale_pid()
112 print(f'✓ {self.name} force killed')
113 return True
114
115 except ProcessLookupError:
116 # Already stopped
117 self._cleanup_stale_pid()
118 print(f'✓ {self.name} already stopped')
119 return True
120 except PermissionError:
121 print(f'✗ Permission denied to stop {self.name} (PID {pid})')
122 return False
123
124 def restart(self):
125 """Restart process (must be implemented by subclass)"""
126 raise NotImplementedError('Subclass must implement restart()')
127
128 def status(self) -> dict:
129 """Get process status"""
130 pid = self.get_pid()
131
132 if pid is None:
133 return {
134 'name': self.name,
135 'running': False,
136 'pid': None,
137 }
138
139 return {
140 'name': self.name,
141 'running': True,
142 'pid': pid,
143 'pid_file': str(self.pid_file),
144 }
145
146 def _cleanup_stale_pid(self):
147 """Remove stale PID file"""
148 if self.pid_file.exists():
149 self.pid_file.unlink()
150
151
152def main():
153 """CLI interface for process management"""
154 if len(sys.argv) < 3:
155 print('Usage: python process_manager.py <process_name> <command>')
156 print('Commands: status, stop, pid')
157 sys.exit(1)
158
159 process_name = sys.argv[1]
160 command = sys.argv[2]
161
162 pm = ProcessManager(process_name)
163
164 if command == 'status':
165 status = pm.status()
166 if status['running']:
167 print(f'{process_name}: RUNNING (PID {status["pid"]})')
168 else:
169 print(f'{process_name}: NOT RUNNING')
170
171 elif command == 'stop':
172 pm.stop()
173
174 elif command == 'pid':
175 pid = pm.get_pid()
176 if pid:
177 print(pid)
178 else:
179 print('NOT RUNNING', file=sys.stderr)
180 sys.exit(1)
181
182 else:
183 print(f'Unknown command: {command}')
184 sys.exit(1)
185
186
187if __name__ == '__main__':
188 main()