forked from RaspAP/SamplePlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerJobManager.php
More file actions
67 lines (53 loc) · 1.74 KB
/
DockerJobManager.php
File metadata and controls
67 lines (53 loc) · 1.74 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
<?php
namespace RaspAP\Plugins\Docker;
class DockerJobManager
{
private string $tmpDir = '/tmp';
public function startJob(string $cmd): string
{
$jobId = uniqid('docker_', true);
$logFile = "/tmp/docker_job_{$jobId}.log";
$pidFile = "/tmp/docker_job_{$jobId}.pid";
$fullCmd = $cmd . ' > ' . escapeshellarg($logFile) . ' 2>&1 & echo $!';
exec($fullCmd, $output, $exitCode);
file_put_contents($pidFile, trim($output[0] ?? ''));
return $jobId;
}
public function getJobStatus(string $jobId): array
{
if (!preg_match('/^docker_[a-zA-Z0-9_.]+$/', $jobId)) {
return ['running' => false, 'output' => '', 'done' => true];
}
$logFile = "/tmp/docker_job_{$jobId}.log";
$pidFile = "/tmp/docker_job_{$jobId}.pid";
if (!file_exists($pidFile)) {
return [
'running' => false,
'output' => file_get_contents($logFile) ?: '',
'done' => true,
];
}
$pid = (int) trim(file_get_contents($pidFile));
$running = ($pid > 0) && posix_kill($pid, 0);
$output = file_get_contents($logFile) ?: '';
return [
'running' => $running,
'output' => $output,
'done' => !$running,
];
}
public function cleanupJob(string $jobId): void
{
if (!preg_match('/^docker_[a-zA-Z0-9_.]+$/', $jobId)) {
return;
}
$logFile = "/tmp/docker_job_{$jobId}.log";
$pidFile = "/tmp/docker_job_{$jobId}.pid";
if (file_exists($logFile)) {
unlink($logFile);
}
if (file_exists($pidFile)) {
unlink($pidFile);
}
}
}