-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathBackgroundJob.php
More file actions
326 lines (274 loc) · 8.38 KB
/
Copy pathBackgroundJob.php
File metadata and controls
326 lines (274 loc) · 8.38 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
<?php
namespace Jobby;
use Opis\Closure\SerializableClosure;
class BackgroundJob
{
/**
* @var Helper
*/
protected $helper;
/**
* @var string
*/
protected $job;
/**
* @var string
*/
protected $tmpDir;
/**
* @var array
*/
protected $config;
/**
* @param string $job
* @param array $config
* @param Helper $helper
*/
public function __construct($job, array $config, Helper $helper = null)
{
$this->job = $job;
$this->config = $config + [
'recipients' => null,
'mailer' => null,
'maxRuntime' => null,
'smtpHost' => null,
'smtpPort' => null,
'smtpUsername' => null,
'smtpPassword' => null,
'smtpSender' => null,
'smtpSenderName' => null,
'smtpSecurity' => null,
'runAs' => null,
'environment' => null,
'runOnHost' => null,
'output' => null,
'output_stdout' => null,
'output_stderr' => null,
'dateFormat' => null,
'enabled' => null,
'haltDir' => null,
'mattermostUrl' => null,
'slackChannel' => null,
'slackUrl' => null,
'slackSender' => null,
'mailSubject' => null,
];
$this->config['output_stdout'] = $this->config['output_stdout'] === null ? $this->config['output'] : $this->config['output_stdout'];
$this->config['output_stderr'] = $this->config['output_stderr'] === null ? $this->config['output'] : $this->config['output_stderr'];
$this->helper = $helper ?: new Helper();
$this->tmpDir = $this->helper->getTempDir();
}
public function run()
{
$lockFile = $this->getLockFile();
try {
$this->checkMaxRuntime($lockFile);
} catch (Exception $e) {
$this->log('ERROR: ' . $e->getMessage(), 'stderr');
$this->notify($e->getMessage());
return;
}
if (!$this->shouldRun()) {
return;
}
$lockAcquired = false;
try {
$this->helper->acquireLock($lockFile);
$lockAcquired = true;
if (isset($this->config['closure'])) {
$this->runFunction();
} else {
$this->runFile();
}
} catch (InfoException $e) {
$this->log('INFO: ' . $e->getMessage(), 'stderr');
} catch (Exception $e) {
$this->log('ERROR: ' . $e->getMessage(), 'stderr');
$this->notify($e->getMessage());
}
if ($lockAcquired) {
$this->helper->releaseLock($lockFile);
// remove log file if empty
$logfile = $this->getLogfile();
if (is_file($logfile) && (filesize($logfile) <= 2 || file_get_contents($logfile) == "[]")) {
unlink($logfile);
}
}
}
/**
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* @param string $lockFile
*
* @throws Exception
*/
protected function checkMaxRuntime($lockFile)
{
$maxRuntime = $this->config['maxRuntime'];
if ($maxRuntime === null) {
return;
}
if ($this->helper->getPlatform() === Helper::WINDOWS) {
throw new Exception('"maxRuntime" is not supported on Windows');
}
$runtime = $this->helper->getLockLifetime($lockFile);
if ($runtime < $maxRuntime) {
return;
}
throw new Exception("MaxRuntime of $maxRuntime secs exceeded! Current runtime: $runtime secs");
}
/**
* @param string $message
* Deprecated
*/
protected function mail($message)
{
if (empty($this->config['recipients'])) {
return;
}
$this->helper->sendMail(
$this->job,
$this->config,
$message
);
}
/**
* @param string $message
*/
protected function notify($message)
{
if (!empty($this->config['recipients'])) {
$this->helper->sendMail(
$this->job,
$this->config,
$message
);
}
if (!empty($this->config['mattermostUrl'])) {
$this->helper->sendMattermostAlert(
$this->job,
$this->config,
$message
);
}
if (!empty($this->config['slackChannel']) && !empty($this->config['slackUrl'])) {
$this->helper->sendSlackAlert(
$this->job,
$this->config,
$message
);
}
}
/**
* @param string $output
* @return string
*/
protected function getLogfile($output = 'stdout')
{
$logfile = $this->config['output_'.$output];
if ($logfile === null) {
return false;
}
$logs = dirname($logfile);
if (!file_exists($logs)) {
mkdir($logs, 0755, true);
}
return $logfile;
}
/**
* @return string
*/
protected function getLockFile()
{
$tmp = $this->tmpDir;
$job = $this->helper->escape($this->job);
if (!empty($this->config['environment'])) {
$env = $this->helper->escape($this->config['environment']);
return "$tmp/$env-$job.lck";
} else {
return "$tmp/$job.lck";
}
}
/**
* @return bool
*/
protected function shouldRun()
{
if (!$this->config['enabled']) {
return false;
}
if (($haltDir = $this->config['haltDir']) !== null) {
if (file_exists($haltDir . DIRECTORY_SEPARATOR . $this->job)) {
return false;
}
}
$host = $this->helper->getHost();
if (strcasecmp($this->config['runOnHost'], $host) != 0) {
return false;
}
return true;
}
/**
* @param string $message
* @param string $output
*/
protected function log($message, $output = 'stdout')
{
$now = date($this->config['dateFormat'], $_SERVER['REQUEST_TIME']);
if ($logfile = $this->getLogfile($output)) {
file_put_contents($logfile, "[$now] [$this->job] $message\n", FILE_APPEND);
}
}
protected function runFunction()
{
$command = unserialize($this->config['closure']);
ob_start();
try {
$retval = $command();
} catch (\Throwable $e) {
if ($logfile = $this->getLogfile('stderr')) {
file_put_contents($this->getLogfile('stderr'), "Error! " . $e->getMessage() . "\n", FILE_APPEND);
}
$retval = $e->getMessage();
}
$content = ob_get_contents();
if ($logfile = $this->getLogfile()) {
file_put_contents($this->getLogfile(), $content, FILE_APPEND);
}
ob_end_clean();
if ($retval !== true) {
throw new Exception("Closure did not return true! Returned:\n" . print_r($retval, true));
}
}
protected function runFile()
{
// If job should run as another user, we must be on *nix and
// must have sudo privileges.
$isUnix = ($this->helper->getPlatform() === Helper::UNIX);
$useSudo = '';
if ($isUnix) {
$runAs = $this->config['runAs'];
$isRoot = (posix_getuid() === 0);
if (!empty($runAs) && $isRoot) {
$useSudo = "sudo -u $runAs";
}
}
// Start execution. Run in foreground (will block).
$command = $this->config['command'];
$stdoutLogfile = $this->getLogfile() ?: $this->helper->getSystemNullDevice();
$stderrLogfile = $this->getLogfile('stderr') ?: $this->helper->getSystemNullDevice();
$command = "$useSudo $command 1>> \"$stdoutLogfile\" 2>> \"$stderrLogfile\"";
if (!$isUnix && $stdoutLogfile === $stderrLogfile) {
$command = "$useSudo $command >> \"$stdoutLogfile\" 2>&1";
}
exec($command, $dummy, $retval);
if ($retval !== 0) {
throw new Exception("Job exited with status '$retval'.");
}
}
}