askrobots / postblob Public

An experimental web framework where PostgreSQL does everything: routing, HTML, file storage, jobs and sessions.

0 downloads

postblob/postblob_ctl.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/postblob.git
HTTPS
https://gitstable.com/git/askrobots/postblob.git
SSH
ssh://git@gitstable.com:2222/askrobots/postblob.git

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

danq9 docs: Add screenshots to README ae44e69 1 year, 1 month ago History
postblob_ctl.py · 10.0 KB · 336 lines
1#!/usr/bin/env python3
2"""
3PostBlob Process Manager - Manage PostBlob server processes via PID files
4"""
5
6import os
7import sys
8import signal
9import argparse
10import subprocess
11import time
12from pathlib import Path
13
14def find_pid_files():
15 """Find all PostBlob PID files in current directory"""
16 return list(Path(".").glob("postblob*.pid"))
17
18def read_pid(pid_file):
19 """Read PID from file"""
20 try:
21 with open(pid_file, 'r') as f:
22 return int(f.read().strip())
23 except (FileNotFoundError, ValueError):
24 return None
25
26def is_process_running(pid):
27 """Check if a process is running"""
28 try:
29 os.kill(pid, 0)
30 return True
31 except OSError:
32 return False
33
34def stop_process(pid_file):
35 """Stop a process using its PID file"""
36 pid = read_pid(pid_file)
37 if not pid:
38 print(f"❌ Could not read PID from {pid_file}")
39 return False
40
41 if not is_process_running(pid):
42 print(f"⚠️ Process {pid} ({pid_file}) is not running")
43 os.remove(pid_file)
44 return True
45
46 try:
47 print(f"🛑 Stopping process {pid} ({pid_file})")
48 os.kill(pid, signal.SIGTERM)
49
50 # Wait for graceful shutdown
51 for _ in range(10):
52 time.sleep(0.5)
53 if not is_process_running(pid):
54 break
55 else:
56 # Force kill if still running
57 print(f"⚠️ Force killing process {pid}")
58 os.kill(pid, signal.SIGKILL)
59
60 # Clean up PID file
61 if os.path.exists(pid_file):
62 os.remove(pid_file)
63
64 print(f"✅ Process {pid} stopped")
65 return True
66 except Exception as e:
67 print(f"❌ Failed to stop process {pid}: {e}")
68 return False
69
70def start_server(port=8002, mode='server'):
71 """Start a PostBlob server"""
72 pid_file = f"postblob_{port}.pid" if mode == 'server' else "postblob_worker.pid"
73
74 # Check if already running
75 if os.path.exists(pid_file):
76 pid = read_pid(pid_file)
77 if pid and is_process_running(pid):
78 print(f"⚠️ Process already running with PID {pid}")
79 return False
80 else:
81 os.remove(pid_file)
82
83 # Start new process
84 cmd = ["python", "server.py", mode]
85 if mode == 'server':
86 cmd.extend(["--port", str(port)])
87
88 print(f"🚀 Starting PostBlob {mode} on port {port}..." if mode == 'server' else f"🚀 Starting PostBlob {mode}...")
89
90 # Use subprocess.Popen to start in background
91 process = subprocess.Popen(
92 cmd,
93 stdout=subprocess.PIPE,
94 stderr=subprocess.PIPE,
95 start_new_session=True
96 )
97
98 # Wait a moment to ensure it started
99 time.sleep(1)
100
101 if process.poll() is None:
102 print(f"✅ Started with PID {process.pid}")
103 return True
104 else:
105 print(f"❌ Failed to start {mode}")
106 return False
107
108def restart_process(pid_file):
109 """Restart a process"""
110 # Determine what kind of process this is
111 if 'worker' in str(pid_file):
112 mode = 'worker'
113 port = None
114 else:
115 mode = 'server'
116 # Extract port from filename
117 port_str = str(pid_file).replace('postblob_', '').replace('.pid', '')
118 try:
119 port = int(port_str)
120 except ValueError:
121 port = 8002
122
123 # Stop existing process
124 print(f"🔄 Restarting {pid_file}...")
125 stop_process(pid_file)
126
127 # Start new process
128 time.sleep(1)
129 if mode == 'worker':
130 return start_server(mode='worker')
131 else:
132 return start_server(port=port, mode=mode)
133
134def status():
135 """Show status of all PostBlob processes"""
136 pid_files = find_pid_files()
137
138 if not pid_files:
139 print("📊 No PostBlob processes found")
140 return
141
142 print("📊 PostBlob Process Status")
143 print("-" * 40)
144
145 for pid_file in pid_files:
146 pid = read_pid(pid_file)
147 if pid:
148 if is_process_running(pid):
149 print(f"✅ {pid_file}: PID {pid} - Running")
150 else:
151 print(f"❌ {pid_file}: PID {pid} - Not running (stale PID file)")
152 else:
153 print(f"⚠️ {pid_file}: Could not read PID")
154
155def stop_all():
156 """Stop all PostBlob processes"""
157 pid_files = find_pid_files()
158
159 if not pid_files:
160 print("📊 No PostBlob processes to stop")
161 return
162
163 print(f"🛑 Stopping {len(pid_files)} PostBlob process(es)...")
164
165 for pid_file in pid_files:
166 stop_process(pid_file)
167
168def restart_all():
169 """Restart all PostBlob processes"""
170 pid_files = find_pid_files()
171
172 if not pid_files:
173 print("📊 No PostBlob processes to restart")
174 return
175
176 print(f"🔄 Restarting {len(pid_files)} PostBlob process(es)...")
177
178 for pid_file in pid_files:
179 restart_process(pid_file)
180
181def backup(output_file=None):
182 """Backup PostBlob database"""
183 from datetime import datetime
184
185 if not output_file:
186 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
187 output_file = f"postblob_backup_{timestamp}.sql"
188
189 print(f"💾 Backing up PostBlob database to {output_file}...")
190
191 try:
192 # Run pg_dump
193 result = subprocess.run(
194 ["pg_dump", "-d", "postblob", "-f", output_file],
195 capture_output=True,
196 text=True
197 )
198
199 if result.returncode == 0:
200 # Check file size
201 size = os.path.getsize(output_file)
202 size_mb = size / (1024 * 1024)
203 print(f"✅ Backup complete: {output_file} ({size_mb:.2f} MB)")
204 return True
205 else:
206 print(f"❌ Backup failed: {result.stderr}")
207 return False
208
209 except Exception as e:
210 print(f"❌ Backup error: {e}")
211 return False
212
213def restore(backup_file):
214 """Restore PostBlob database from backup"""
215 if not os.path.exists(backup_file):
216 print(f"❌ Backup file not found: {backup_file}")
217 return False
218
219 print(f"📥 Restoring PostBlob database from {backup_file}...")
220 print("⚠️ WARNING: This will overwrite the current database!")
221
222 response = input("Continue? (y/N): ")
223 if response.lower() != 'y':
224 print("❌ Restore cancelled")
225 return False
226
227 try:
228 # Run psql to restore
229 result = subprocess.run(
230 ["psql", "-d", "postblob", "-f", backup_file],
231 capture_output=True,
232 text=True
233 )
234
235 if result.returncode == 0:
236 print(f"✅ Restore complete from {backup_file}")
237 return True
238 else:
239 print(f"❌ Restore failed: {result.stderr}")
240 return False
241
242 except Exception as e:
243 print(f"❌ Restore error: {e}")
244 return False
245
246def main():
247 parser = argparse.ArgumentParser(
248 description='PostBlob Process Manager',
249 formatter_class=argparse.RawDescriptionHelpFormatter,
250 epilog="""
251Examples:
252 %(prog)s status # Show status of all processes
253 %(prog)s start # Start server on default port (8002)
254 %(prog)s start --port 8003 # Start server on specific port
255 %(prog)s start --mode worker # Start worker process
256 %(prog)s stop postblob_8002.pid # Stop specific process
257 %(prog)s stop --all # Stop all processes
258 %(prog)s restart postblob_8002.pid # Restart specific process
259 %(prog)s restart --all # Restart all processes
260 %(prog)s backup # Create timestamped backup
261 %(prog)s backup -o custom.sql # Backup to specific file
262 %(prog)s restore backup.sql # Restore from backup file
263 """
264 )
265
266 subparsers = parser.add_subparsers(dest='command', help='Commands')
267
268 # Status command
269 status_parser = subparsers.add_parser('status', help='Show process status')
270
271 # Start command
272 start_parser = subparsers.add_parser('start', help='Start a new process')
273 start_parser.add_argument('--port', type=int, default=8002, help='Server port (default: 8002)')
274 start_parser.add_argument('--mode', choices=['server', 'worker', 'all'], default='server',
275 help='Process mode (default: server)')
276
277 # Stop command
278 stop_parser = subparsers.add_parser('stop', help='Stop process(es)')
279 stop_parser.add_argument('pid_file', nargs='?', help='PID file to stop')
280 stop_parser.add_argument('--all', action='store_true', help='Stop all processes')
281
282 # Restart command
283 restart_parser = subparsers.add_parser('restart', help='Restart process(es)')
284 restart_parser.add_argument('pid_file', nargs='?', help='PID file to restart')
285 restart_parser.add_argument('--all', action='store_true', help='Restart all processes')
286
287 # Backup command
288 backup_parser = subparsers.add_parser('backup', help='Backup database')
289 backup_parser.add_argument('-o', '--output', help='Output file (default: timestamped)')
290
291 # Restore command
292 restore_parser = subparsers.add_parser('restore', help='Restore database from backup')
293 restore_parser.add_argument('backup_file', help='Backup file to restore from')
294
295 args = parser.parse_args()
296
297 if not args.command:
298 parser.print_help()
299 sys.exit(1)
300
301 if args.command == 'status':
302 status()
303
304 elif args.command == 'start':
305 if args.mode == 'all':
306 start_server(port=args.port, mode='server')
307 start_server(mode='worker')
308 elif args.mode == 'worker':
309 start_server(mode='worker')
310 else:
311 start_server(port=args.port, mode='server')
312
313 elif args.command == 'stop':
314 if args.all:
315 stop_all()
316 elif args.pid_file:
317 stop_process(Path(args.pid_file))
318 else:
319 print("❌ Please specify a PID file or use --all")
320
321 elif args.command == 'restart':
322 if args.all:
323 restart_all()
324 elif args.pid_file:
325 restart_process(Path(args.pid_file))
326 else:
327 print("❌ Please specify a PID file or use --all")
328
329 elif args.command == 'backup':
330 backup(args.output)
331
332 elif args.command == 'restore':
333 restore(args.backup_file)
334
335if __name__ == '__main__':
336 main()