forked from doppar/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCronDaemonCommand.php
More file actions
333 lines (277 loc) · 8.59 KB
/
CronDaemonCommand.php
File metadata and controls
333 lines (277 loc) · 8.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
namespace Phaseolies\Console\Commands\Cron;
use Phaseolies\Console\Schedule\Command;
class CronDaemonCommand extends Command
{
/**
* The name of the console command.
*
* @var string
*/
protected $name = 'cron:daemon {action : start, stop, restart, or status}';
/**
* The description of the console command.
*
* @var string
*/
protected $description = 'Manage the cron daemon for second-based schedules';
/**
* Execute the console command.
* Example: php doppar cron:daemon start|stop|restart|status
*
* @return int
*/
public function handle(): int
{
$action = $this->argument('action');
return match ($action) {
'start' => $this->startDaemon(),
'stop' => $this->stopDaemon(),
'restart' => $this->restartDaemon(),
'status' => $this->showStatus(),
default => $this->invalidAction($action)
};
}
/**
* Start the daemon
*
* @return int
*/
protected function startDaemon(): int
{
if ($this->isDaemonRunning()) {
$this->displayWarning('Daemon is already running!');
return Command::FAILURE;
}
$this->displayInfo('Starting cron daemon...');
$phpBinary = PHP_BINARY;
$poolScript = base_path('pool');
$logFile = storage_path('schedule/daemon.log');
$logDir = dirname($logFile);
if (!file_exists($logDir)) {
mkdir($logDir, 0755, true);
}
// Start daemon in background
$command = sprintf(
'%s %s cron:run --daemon >> %s 2>&1 & echo $!',
escapeshellarg($phpBinary),
escapeshellarg($poolScript),
escapeshellarg($logFile)
);
$pid = (int) shell_exec($command);
if ($pid > 0) {
// Wait a moment and verify it's running
// 0.5 seconds
usleep(500000);
if ($this->isProcessRunning($pid)) {
$this->displaySuccess(sprintf(
'Daemon started successfully (PID: %d)',
$pid
));
$this->displayInfo("Log file: {$logFile}");
return Command::SUCCESS;
} else {
$this->displayError('Daemon started but stopped immediately. Check logs.');
return Command::FAILURE;
}
}
$this->displayError('Failed to start daemon');
return Command::FAILURE;
}
/**
* Stop the daemon
*
* @return int
*/
protected function stopDaemon(): int
{
if (!$this->isDaemonRunning()) {
$this->displayWarning('Daemon is not running!');
return Command::FAILURE;
}
$pidFile = $this->getDaemonPidFile();
$data = @json_decode(file_get_contents($pidFile), true);
$pid = $data['pid'] ?? 0;
$this->displayInfo("Stopping daemon (PID: {$pid})...");
// Try graceful shutdown first
if (function_exists('posix_kill')) {
posix_kill($pid, SIGTERM);
} else {
// Fallback for systems without posix_kill
exec("kill {$pid}");
}
// Wait up to 5 seconds for graceful shutdown
$waited = 0;
while ($waited < 5 && $this->isProcessRunning($pid)) {
// 0.5 seconds
usleep(500000);
$waited += 0.5;
}
// Force kill if still running
if ($this->isProcessRunning($pid)) {
$this->displayWarning('Daemon did not stop gracefully, forcing...');
if (function_exists('posix_kill')) {
posix_kill($pid, SIGKILL);
} else {
exec("kill -9 {$pid}");
}
usleep(500000);
}
// Verify stopped and clean up
if (!$this->isProcessRunning($pid)) {
if (file_exists($pidFile)) {
unlink($pidFile);
}
$this->displaySuccess('Daemon stopped successfully');
return Command::SUCCESS;
}
$this->displayError('Failed to stop daemon');
return Command::FAILURE;
}
/**
* Restart the daemon
*
* @return int
*/
protected function restartDaemon(): int
{
$this->displayInfo('Restarting daemon...');
if ($this->isDaemonRunning()) {
$stopResult = $this->stopDaemon();
if ($stopResult !== Command::SUCCESS) {
return $stopResult;
}
// Wait a moment before starting
sleep(1);
}
return $this->startDaemon();
}
/**
* Show daemon status
*
* @return int
*/
protected function showStatus(): int
{
$pidFile = $this->getDaemonPidFile();
if (!$this->isDaemonRunning()) {
$this->displayWarning('Daemon is NOT running');
if (file_exists($pidFile)) {
$this->displayInfo('Stale PID file exists, cleaning up...');
unlink($pidFile);
}
return Command::SUCCESS;
}
$data = @json_decode(file_get_contents($pidFile), true);
$this->displaySuccess('Daemon is RUNNING');
$this->line('');
$this->line('<info>Process Information:</info>');
$this->line(" PID: {$data['pid']}");
$this->line(" Started: {$data['started_at']}");
$this->line(" PHP Version: {$data['php_version']}");
$this->line(" OS: {$data['os']}");
$startTime = strtotime($data['started_at']);
$uptime = time() - $startTime;
$this->line(" Uptime: " . $this->formatUptime($uptime));
$logFile = storage_path('schedule/daemon.log');
if (file_exists($logFile)) {
$this->line(" Log: {$logFile}");
$this->line(" Log Size: " . $this->formatBytes(filesize($logFile)));
}
return Command::SUCCESS;
}
/**
* Handle invalid action
*
* @param string $action
* @return int
*/
protected function invalidAction(string $action): int
{
$this->displayError("Invalid action: {$action}");
$this->line('');
$this->line('Available actions:');
$this->line(' <comment>start</comment> - Start the daemon');
$this->line(' <comment>stop</comment> - Stop the daemon');
$this->line(' <comment>restart</comment> - Restart the daemon');
$this->line(' <comment>status</comment> - Show daemon status');
return Command::FAILURE;
}
/**
* Check if daemon is running
*
* @return bool
*/
protected function isDaemonRunning(): bool
{
$pidFile = $this->getDaemonPidFile();
if (!file_exists($pidFile)) {
return false;
}
$data = @json_decode(file_get_contents($pidFile), true);
$pid = $data['pid'] ?? 0;
return $this->isProcessRunning($pid);
}
/**
* Check if a process is running
*
* @param int $pid
* @return bool
*/
protected function isProcessRunning(int $pid): bool
{
if ($pid <= 0) {
return false;
}
if (function_exists('posix_kill')) {
return posix_kill($pid, 0);
}
// Fallback
$output = shell_exec(sprintf("ps -p %d -o pid=", $pid));
return !empty(trim($output));
}
/**
* Get daemon PID file path
*
* @return string
*/
protected function getDaemonPidFile(): string
{
return storage_path('schedule/cron_daemon.pid');
}
/**
* Format uptime in human readable format
*
* @param int $seconds
* @return string
*/
protected function formatUptime(int $seconds): string
{
$days = floor($seconds / 86400);
$hours = floor(($seconds % 86400) / 3600);
$minutes = floor(($seconds % 3600) / 60);
$secs = $seconds % 60;
$parts = [];
if ($days > 0) $parts[] = "{$days}d";
if ($hours > 0) $parts[] = "{$hours}h";
if ($minutes > 0) $parts[] = "{$minutes}m";
if ($secs > 0 || empty($parts)) $parts[] = "{$secs}s";
return implode(' ', $parts);
}
/**
* Format bytes in human readable format
*
* @param int $bytes
* @return string
*/
protected function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
}