-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackgroundPHPTasksManager.php
342 lines (285 loc) · 8.35 KB
/
BackgroundPHPTasksManager.php
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
334
335
336
337
338
339
340
341
342
<?php
class BackgroundTasksManager
{
/**
* The BackgroundTasksManager class.
*
* @category Process
* @package BackgroundPHPTask
* @author gnieark <[email protected]>
* @license GNU General Public License V3
* @link https://github.com/gnieark/BackgroundPHPtasks
*/
/**
* Writable directory where pid file, logs and output are stored
*
* @var string
*/
private $base_path;
/**
* list containing BackgroundTasks objects
*
* @var string
*/
private $tasks = array();
/**
* Return the pid file used by default for tasks in queue
*
* @return string
*/
private function get_pid_file_path()
{
return $this->base_path . "/TaskManager.pid";
}
/**
* The goal is to manage long time process. The object have to be reloadable
* so, after some changes
* the current object is serialized and saved. This give the backup file
*
* @return string
*/
private function get_backup_file()
{
return $this->base_path . "/TaskManager.serialized";
}
/**
* If the daemon is launched, it uses a specific PID file
*
* @return string
*/
private function get_daemon_pid_file()
{
return $this->base_path . "/taskmanagerDaemon.pid";
}
/**
* Construct function
*
* @param string $base_path Writable path.
*/
public function __construct($base_path)
{
$this->base_path = $base_path;
$this->load();
}
/**
* Check for an exixting backup un the base path
* and load it on the current object
*
* @return BackgroundTasksManager for chaining
*/
public function load(){
if(file_exists($this->get_backup_file())){
$arr = unserialize (file_get_contents( $this->get_backup_file() ));
$this->base_path = $arr['base_path'];
$this->tasks = $arr['tasks'];
}
return $this;
}
/**
* Serialize current object and store it
*
* @return BackgroundTasksManager for chaining
*/
public function save(){
$arr = array(
"base_path" => $this->base_path,
"tasks" => $this->tasks
);
file_put_contents($this->get_backup_file() , serialize($arr));
return $this;
}
/**
* Add a task on queue
*
* @param $backgroundPHPTask a BackgroundPHPTask object to add on queue
* if not running will be executed only when no others tasks are terminated.
* @param $startnow If is true, it wil be launched now
*
* @return BackgroundTasksManager for chaining
*/
public function add_task_on_queue (BackgroundPHPTask $backgroundPHPTask, bool $startnow = false)
{
if(empty($backgroundPHPTask->get_pifFile() ))
{
$backgroundPHPTask-> set_pidFile ( $this->get_pid_file_path() );
}
if($startnow && !($backgroundPHPTask->get_status() == "running") )
{
$backgroundPHPTask->exec();
}
$this->tasks[] = $backgroundPHPTask;
$this->check_queue();
return $this;
}
/**
* check queue
* and evntentualy exec the oldest pending task
* @return BackgroundTasksManager for chaining
*/
public function check_queue()
{
$lastStatus = "terminated";
foreach($this->tasks as $task)
{
if( $task->get_status() == "running" )
{
$this->save();
return $this;
}elseif($task->get_status() == "pending"){
$task->exec();
$this->save();
return $this;
}
}
$this->save();
return $this;
}
/**
* Use the pid, and test (Linux only) if running
* @return bool
*/
public function is_daemon_running()
{
if(!file_exists($this->get_daemon_pid_file())){
return false;
}
$data = file($this->get_daemon_pid_file());
$daemonPid = intval( $data[count($data) -1] );
return $daemonPid ;
}
/**
* kill the process
* @return BackgroundTasksManager for chaining
*/
public function daemon_stop()
{
$daemonPid = $this->is_daemon_running();
if($daemonPid)
{
posix_kill( $daemonPid, SIGTERM );
unlink($this->get_daemon_pid_file());
}
return $this;
}
/**
* Launch a process witch will check_queue regularly
* @param integer $delay : seconds
* @return BackgroundTasksManager for chaining
*/
public function daemonize_check_queue($delay = 10)
{
$this->daemon_stop();
$rfBackgroundTasksManager = new \ReflectionClass ('BackgroundTasksManager');
$BackgroundTasksManagerClassFile = $rfBackgroundTasksManager->getFileName();
$rfBackgroundPHPTask = new \ReflectionClass ('BackgroundPHPTask');
$BackgroundPHPTaskClassFile = $rfBackgroundPHPTask->getFileName();
$daemonScript =
'<?php
require_once("' . $BackgroundTasksManagerClassFile . '");
require_once("' . $BackgroundPHPTaskClassFile . '");
$taskManager = new BackgroundTasksManager("' . $this->base_path . '");
while(1)
{
$taskManager->load();
$taskManager->check_queue();
sleep(' . $delay .');
}
'
;
$daemonTask = new BackgroundPHPTask();
$daemonTask ->set_pidFile( $this->get_daemon_pid_file() )
->set_phpScriptWithoutFile($daemonScript)
->exec();
return $this;
}
/**
* kills an remove files
* @return BackgroundTasksManager for chaining
*
*/
public function purge_terminated_tasks()
{
for ($i = 0; $i < count ($this->tasks); $i++)
{
if( $this->tasks[$i]->get_status() == "terminated" )
{
unset($this->tasks[$i]);
}
}
$this->clean_pid_file(true);
$this->save();
return $this;
}
/**
* If many pids on pid file, remove unknowed ones
*
* @return BackgroundTasksManager for chaining
*
*/
private function clean_pid_file($killUnknowedProcess = false)
{
$existingPids = array();
foreach( $this->tasks as $task)
{
if(!empty($task->get_pid()))
{
$existingPids[] = $task->get_pid();
}
}
if ($killUnknowedProcess)
{
$pidFileResource = @fopen($this->get_pid_file_path(), "r");
if($pidFileResource)
{
while (($pidLine = fgets($pidFileResource, 4096)) !== false) {
if ((!in_array($buffer, $existingPids)) && ($this->isProcessRunning($buffer)))
{
posix_kill( $buffer, SIGTERM );
}
}
}
fclose($pidFileResource);
}
$pidFileResource = fopen($this->get_pid_file_path());
if (flock($pidFileResource, LOCK_EX)) { // lock
ftruncate($pidFileResource, 0);
foreach($existingPids as $pid) {
fwrite($pidFileResource, $pid . "\n");
}
fflush($pidFileResource);
flock($pidFileResource, LOCK_UN);
} else {
throw new LockException('Could not lock the pidfile');
}
fclose( $this->get_pid_file_path() );
}
/**
* check if a process is running
*
* @return bool
*
*/
private function isProcessRunning($pid)
{
// Warning: this will only work on Unix
return ($pid !== '') && file_exists("/proc/$pid");
}
/**
* stop all running tasks, remove PID file and knowed output files
*
* @return BackgroundTasksManager for chaining
*
*/
public function stop_and_remove()
{
foreach($this->tasks as $task)
{
$task->stop()->remove_output_file();
}
$this->daemon_stop();
@unlink ( $this->get_pid_file_path() );
@unlink ( $this->get_backup_file() );
@unlink ( $this->get_daemon_pid_file() );
return $this;
}
}