forked from brianlmoon/GearmanManager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GearmanManager.php
1184 lines (961 loc) · 35.9 KB
/
GearmanManager.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
*
*PHP script for managing PHP based Gearman workers
*
*Copyright (c) 2010, Brian Moon
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Brian Moon nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
*LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*POSSIBILITY OF SUCH DAMAGE.
*
**/
declare(ticks = 1);
error_reporting(E_ALL | E_STRICT);
require dirname(__FILE__)."/JobFailProtection.php";
/**
* Class that handles all the process management
*/
abstract class GearmanManager {
/**
* Log levels can be enabled from the command line with -v, -vv, -vvv
*/
const LOG_LEVEL_INFO = 1;
const LOG_LEVEL_PROC_INFO = 2;
const LOG_LEVEL_WORKER_INFO = 3;
const LOG_LEVEL_DEBUG = 4;
const LOG_LEVEL_CRAZY = 5;
/**
* Default config section name
*/
const DEFAULT_CONFIG = "GearmanManager";
/**
* Defines job priority limits
*/
const MIN_PRIORITY = -5;
const MAX_PRIORITY = 5;
/**
* Holds the worker configuration
*/
protected $config = array();
/**
* Boolean value that determines if the running code is the parent or a child
*/
protected $isparent = true;
/**
* When true, workers will stop look for jobs and the parent process will
* kill off all running children
*/
protected $stop_work = false;
/**
* The timestamp when the signal was received to stop working
*/
protected $stop_time = 0;
/**
* The filename to log to
*/
protected $log_file;
/**
* Holds the resource for the log file
*/
protected $log_file_handle;
/**
* Flag for logging to syslog
*/
protected $log_syslog = false;
/**
* Verbosity level for the running script. Set via -v option
*/
protected $verbose = 0;
/**
* The array of running child processes
*/
protected $children = array();
/**
* The array of jobs that have workers running
*/
protected $jobs = array();
/**
* The PID of the running process. Set for parent and child processes
*/
protected $pid = 0;
/**
* The PID of the parent process, when running in the forked helper.
*/
protected $parent_pid = 0;
/**
* PID file for the parent process
*/
protected $pid_file = "";
/**
* PID of helper child
*/
protected $helper_pid = 0;
/**
* The user to run as
*/
protected $user = null;
/**
* If true, the worker code directory is checked for updates and workers
* are restarted automatically.
*/
protected $check_code = false;
/**
* Holds the last timestamp of when the code was checked for updates
*/
protected $last_check_time = 0;
/**
* When forking helper children, the parent waits for a signal from them
* to continue doing anything
*/
protected $wait_for_signal = false;
/**
* Directory where worker functions are found
*/
protected $worker_dir = "";
/**
* Number of workers that do all jobs
*/
protected $do_all_count = 0;
/**
* Maximum time a worker will run
*/
protected $max_run_time = 3600;
/**
* +/- number of minutes workers will delay before restarting
* this prevents all your workers from restarting at the same
* time which causes a connection stampeded on your daemons
* So, a max_run_time of 3600 and worker_restart_splay of 600 means
* a worker will self restart between 3600 and 4200 seconds after
* it is started.
*
* This does not affect the time the parent process waits on children
* when shutting down.
*/
protected $worker_restart_splay = 600;
/**
* Maximum number of jobs this worker will do before quitting
*/
protected $max_job_count = 0;
/**
* Maximum job iterations per worker
*/
protected $max_runs_per_worker = null;
/**
* Number of times this worker has run a job
*/
protected $job_execution_count = 0;
/**
* Servers that workers connect to
*/
protected $servers = array();
/**
* List of functions available for work
*/
protected $functions = array();
/**
* Function/Class prefix
*/
protected $prefix = "";
/**
* Creates the manager and gets things going
*
*/
public function __construct() {
if(!function_exists("posix_kill")){
$this->show_help("The function posix_kill was not found. Please ensure POSIX functions are installed");
}
if(!function_exists("pcntl_fork")){
$this->show_help("The function pcntl_fork was not found. Please ensure Process Control functions are installed");
}
$this->pid = getmypid();
/**
* Parse command line options. Loads the config file as well
*/
$this->getopt();
/**
* Register signal listeners
*/
$this->register_ticks();
/**
* Load up the workers
*/
$this->load_workers();
if(empty($this->functions)){
$this->log("No workers found");
posix_kill($this->pid, SIGUSR1);
exit();
}
/**
* Validate workers in the helper process
*/
$this->fork_me("validate_workers");
$this->log("Started with pid $this->pid", GearmanManager::LOG_LEVEL_PROC_INFO);
/**
* Start the initial workers and set up a running environment
*/
$this->bootstrap();
$this->process_loop();
/**
* Kill the helper if it is running
*/
if(isset($this->helper_pid)){
posix_kill($this->helper_pid, SIGKILL);
}
$this->log("Exiting");
}
protected function process_loop() {
/**
* Main processing loop for the parent process
*/
while(!$this->stop_work || count($this->children)) {
$status = null;
/**
* Check for exited children
*/
$exited = pcntl_wait( $status, WNOHANG );
/**
* We run other children, make sure this is a worker
*/
if(isset($this->children[$exited])){
/**
* If they have exited, remove them from the children array
* If we are not stopping work, start another in its place
*/
if($exited) {
$worker = $this->children[$exited]['job'];
unset($this->children[$exited]);
$code = pcntl_wexitstatus($status);
$this->log("Child $exited exited with error code of $code (".implode(",", $worker).")", GearmanManager::LOG_LEVEL_PROC_INFO);
if(!$this->stop_work){
$this->start_worker($worker);
}
}
}
if($this->stop_work && time() - $this->stop_time > 60){
$this->log("Children have not exited, killing.", GearmanManager::LOG_LEVEL_PROC_INFO);
$this->stop_children(SIGKILL);
} else {
/**
* If any children have been running 150% of max run time, forcibly terminate them
*/
if (!empty($this->children)) {
foreach($this->children as $pid => $child) {
if (!empty($child['start_time']) && time() - $child['start_time'] > $this->max_run_time * 1.5) {
$this->log("Child $pid has been running too long. Forcibly killing process. (".implode(",", $child['job']).")", GearmanManager::LOG_LEVEL_PROC_INFO);
posix_kill($pid, SIGKILL);
}
}
}
}
/**
* php will eat up your cpu if you don't have this
*/
usleep(50000);
}
}
/**
* Handles anything we need to do when we are shutting down
*
*/
public function __destruct() {
if($this->isparent){
if(!empty($this->pid_file) && file_exists($this->pid_file)){
if(!unlink($this->pid_file)) {
$this->log("Could not delete PID file", GearmanManager::LOG_LEVEL_PROC_INFO);
}
}
}
}
/**
* Parses the command line options
*
*/
protected function getopt() {
$opts = getopt("ac:dD:h:Hl:o:p:P:u:v::w:r:x:Z");
if(isset($opts["H"])){
$this->show_help();
}
if(isset($opts["c"]) && !file_exists($opts["c"])){
$this->show_help("Config file $opts[c] not found.");
}
/**
* parse the config file
*/
if(isset($opts["c"])){
$this->parse_config($opts["c"]);
}
/**
* command line opts always override config file
*/
if (isset($opts['P'])) {
$this->config['pid_file'] = $opts['P'];
}
if(isset($opts["l"])){
$this->config['log_file'] = $opts["l"];
}
if (isset($opts['a'])) {
$this->config['auto_update'] = 1;
}
if (isset($opts['w'])) {
$this->config['worker_dir'] = $opts['w'];
}
if (isset($opts['x'])) {
$this->config['max_worker_lifetime'] = (int)$opts['x'];
}
if (isset($opts['r'])) {
$this->config['max_runs_per_worker'] = (int)$opts['r'];
}
if (isset($opts['D'])) {
$this->config['count'] = (int)$opts['D'];
}
if (isset($opts['t'])) {
$this->config['timeout'] = $opts['t'];
}
if (isset($opts['h'])) {
$this->config['host'] = $opts['h'];
}
if (isset($opts['p'])) {
$this->prefix = $opts['p'];
} elseif(!empty($this->config['prefix'])) {
$this->prefix = $this->config['prefix'];
}
if (isset($opts['u'])){
$this->user = $opts['u'];
} elseif(isset($this->config["user"])){
$this->user = $this->config["user"];
}
if (isset($opts['n'])) {
$this->config['notify'] = $opts['n'];
}
if (!empty($this->config['notify'])) {
JobFailProtection::$notifyEmail = $this->config['notify'];
}
/**
* If we want to daemonize, fork here and exit
*/
if(isset($opts["d"])){
$pid = pcntl_fork();
if($pid>0){
$this->isparent = false;
exit();
}
$this->pid = getmypid();
posix_setsid();
}
if(!empty($this->config['pid_file'])){
$fp = @fopen($this->config['pid_file'], "w");
if($fp){
fwrite($fp, $this->pid);
fclose($fp);
} else {
$this->show_help("Unable to write PID to {$this->config['pid_file']}");
}
$this->pid_file = $this->config['pid_file'];
}
if(!empty($this->config['log_file'])){
if($this->config['log_file'] === 'syslog'){
$this->log_syslog = true;
} else {
$this->log_file = $this->config['log_file'];
$this->open_log_file();
}
}
if(isset($opts["v"])){
switch($opts["v"]){
case false:
$this->verbose = GearmanManager::LOG_LEVEL_INFO;
break;
case "v":
$this->verbose = GearmanManager::LOG_LEVEL_PROC_INFO;
break;
case "vv":
$this->verbose = GearmanManager::LOG_LEVEL_WORKER_INFO;
break;
case "vvv":
$this->verbose = GearmanManager::LOG_LEVEL_DEBUG;
break;
case "vvvv":
default:
$this->verbose = GearmanManager::LOG_LEVEL_CRAZY;
break;
}
}
if($this->user) {
$user = posix_getpwnam($this->user);
if (!$user || !isset($user['uid'])) {
$this->show_help("User ({$this->user}) not found.");
}
/**
* Ensure new uid can read/write pid and log files
*/
if(!empty($this->pid_file)){
if(!chown($this->pid_file, $user['uid'])){
$this->log("Unable to chown PID file to {$this->user}", GearmanManager::LOG_LEVEL_PROC_INFO);
}
}
if(!empty($this->log_file_handle)){
if(!chown($this->log_file, $user['uid'])){
$this->log("Unable to chown log file to {$this->user}", GearmanManager::LOG_LEVEL_PROC_INFO);
}
}
posix_setuid($user['uid']);
posix_setgid($user['gid']);
if (posix_geteuid() != $user['uid']) {
$this->show_help("Unable to change user to {$this->user} (UID: {$user['uid']}).");
}
$this->log("User set to {$this->user}", GearmanManager::LOG_LEVEL_PROC_INFO);
}
if(!empty($this->config['auto_update'])){
$this->check_code = true;
}
if(!empty($this->config['worker_dir'])){
$this->worker_dir = $this->config['worker_dir'];
} else {
$this->worker_dir = "./workers";
}
$dirs = explode(",", $this->worker_dir);
foreach($dirs as &$dir){
$dir = trim($dir);
if(!file_exists($dir)){
$this->show_help("Worker dir ".$dir." not found");
}
}
unset($dir);
if(isset($this->config['max_worker_lifetime']) && (int)$this->config['max_worker_lifetime'] > 0){
$this->max_run_time = (int)$this->config['max_worker_lifetime'];
}
if(isset($this->config['worker_restart_splay']) && (int)$this->config['worker_restart_splay'] > 0){
$this->worker_restart_splay = (int)$this->config['worker_restart_splay'];
}
if(isset($this->config['count']) && (int)$this->config['count'] > 0){
$this->do_all_count = (int)$this->config['count'];
}
if(!empty($this->config['host'])){
if(!is_array($this->config['host'])){
$this->servers = explode(",", $this->config['host']);
} else {
$this->servers = $this->config['host'];
}
} else {
$this->servers = array("127.0.0.1:4730");
}
if (!empty($this->config['include']) && $this->config['include'] != "*") {
$this->config['include'] = explode(",", $this->config['include']);
} else {
$this->config['include'] = array();
}
if (!empty($this->config['exclude'])) {
$this->config['exclude'] = explode(",", $this->config['exclude']);
} else {
$this->config['exclude'] = array();
}
/**
* Debug option to dump the config and exit
*/
if(isset($opts["Z"])){
print_r($this->config);
exit();
}
}
/**
* Parses the config file
*
* @param string $file The config file. Just pass so we don't have
* to keep it around in a var
*/
protected function parse_config($file) {
$this->log("Loading configuration from $file");
if (substr($file, -4) == ".php"){
require $file;
} elseif(substr($file, -4) == ".ini"){
$gearman_config = parse_ini_file($file, true);
}
if (empty($gearman_config)){
$this->show_help("No configuration found in $file");
}
if (isset($gearman_config[self::DEFAULT_CONFIG])) {
$this->config = $gearman_config[self::DEFAULT_CONFIG];
$this->config['functions'] = array();
}
foreach($gearman_config as $function=>$data){
if (strcasecmp($function, self::DEFAULT_CONFIG) != 0) {
$this->config['functions'][$function] = $data;
}
}
}
/**
* Helper function to load and filter worker files
*
* return @void
*/
protected function load_workers() {
$this->functions = array();
$dirs = explode(",", $this->worker_dir);
foreach($dirs as $dir){
$this->log("Loading workers in ".$dir);
$worker_files = glob($dir."/*.php");
if (!empty($worker_files)) {
foreach($worker_files as $file){
$function = substr(basename($file), 0, -4);
/**
* include workers
*/
if (!empty($this->config['include'])) {
if (!in_array($function, $this->config['include'])) {
continue;
}
}
/**
* exclude workers
*/
if (in_array($function, $this->config['exclude'])) {
continue;
}
if(!isset($this->functions[$function])){
$this->functions[$function] = array();
}
if(!empty($this->config['functions'][$function]['dedicated_only'])){
if(empty($this->config['functions'][$function]['dedicated_count'])){
$this->log("Invalid configuration for dedicated_count for function $function.", GearmanManager::LOG_LEVEL_PROC_INFO);
exit();
}
$this->functions[$function]['dedicated_only'] = true;
$this->functions[$function]["count"] = $this->config['functions'][$function]['dedicated_count'];
} else {
$min_count = max($this->do_all_count, 1);
if(!empty($this->config['functions'][$function]['count'])){
$min_count = max($this->config['functions'][$function]['count'], $this->do_all_count);
}
if(!empty($this->config['functions'][$function]['dedicated_count'])){
$ded_count = $this->do_all_count + $this->config['functions'][$function]['dedicated_count'];
} elseif(!empty($this->config["dedicated_count"])){
$ded_count = $this->do_all_count + $this->config["dedicated_count"];
} else {
$ded_count = $min_count;
}
$this->functions[$function]["count"] = max($min_count, $ded_count);
}
$this->functions[$function]['path'] = $file;
/**
* Note about priority. This exploits an undocumented feature
* of the gearman daemon. This will only work as long as the
* current behavior of the daemon remains the same. It is not
* a defined part fo the protocol.
*/
if(!empty($this->config['functions'][$function]['priority'])){
$priority = max(min(
$this->config['functions'][$function]['priority'],
self::MAX_PRIORITY), self::MIN_PRIORITY);
} else {
$priority = 0;
}
$this->functions[$function]['priority'] = $priority;
}
}
}
}
/**
* Forks the process and runs the given method. The parent then waits
* for the child process to signal back that it can continue
*
* @param string $method Class method to run after forking
*
*/
protected function fork_me($method){
$this->wait_for_signal = true;
$pid = pcntl_fork();
switch($pid) {
case 0:
$this->isparent = false;
$this->parent_pid = $this->pid;
$this->pid = getmypid();
$this->$method();
break;
case -1:
$this->log("Failed to fork");
$this->stop_work = true;
break;
default:
$this->log("Helper forked with pid $pid", GearmanManager::LOG_LEVEL_PROC_INFO);
$this->helper_pid = $pid;
while($this->wait_for_signal && !$this->stop_work) {
usleep(5000);
pcntl_waitpid($pid, $status, WNOHANG);
if (pcntl_wifexited($status) && $status) {
$this->log("Helper child exited with non-zero exit code $status.");
exit(1);
}
}
break;
}
}
/**
* Forked method that validates the worker code and checks it if desired
*
*/
protected function validate_workers(){
$this->load_workers();
if(empty($this->functions)){
$this->log("No workers found");
posix_kill($this->parent_pid, SIGUSR1);
exit();
}
$this->validate_lib_workers();
/**
* Since we got here, all must be ok, send a CONTINUE
*/
$this->log("Helper is running. Sending continue to $this->parent_pid.", GearmanManager::LOG_LEVEL_DEBUG);
posix_kill($this->parent_pid, SIGCONT);
if($this->check_code){
$this->log("Running loop to check for new code", self::LOG_LEVEL_DEBUG);
$last_check_time = 0;
while(1) {
$max_time = 0;
foreach($this->functions as $name => $func){
clearstatcache();
$mtime = filemtime($func['path']);
$max_time = max($max_time, $mtime);
$this->log("{$func['path']} - $mtime $last_check_time", self::LOG_LEVEL_CRAZY);
if($last_check_time!=0 && $mtime > $last_check_time){
$this->log("New code found. Sending SIGHUP", self::LOG_LEVEL_PROC_INFO);
posix_kill($this->parent_pid, SIGHUP);
break;
}
}
$last_check_time = $max_time;
sleep(5);
}
} else {
exit();
}
}
/**
* Bootstap a set of workers and any vars that need to be set
*
*/
protected function bootstrap() {
$function_count = array();
/**
* If we have "do_all" workers, start them first
* do_all workers register all functions
*/
if(!empty($this->do_all_count) && is_int($this->do_all_count)){
for($x=0;$x<$this->do_all_count;$x++){
$this->start_worker();
}
foreach($this->functions as $worker => $settings){
if(empty($settings["dedicated_only"])){
$function_count[$worker] = $this->do_all_count;
}
}
}
/**
* Next we loop the workers and ensure we have enough running
* for each worker
*/
foreach($this->functions as $worker=>$config) {
/**
* If we don't have do_all workers, this won't be set, so we need
* to init it here
*/
if(empty($function_count[$worker])){
$function_count[$worker] = 0;
}
while($function_count[$worker] < $config["count"]){
$this->start_worker($worker);
$function_count[$worker]++;;
}
/**
* php will eat up your cpu if you don't have this
*/
usleep(50000);
}
/**
* Set the last code check time to now since we just loaded all the code
*/
$this->last_check_time = time();
}
protected function start_worker($worker="all") {
static $all_workers;
if(is_array($worker)){
$worker_list = $worker;
} elseif($worker == "all"){
if(is_null($all_workers)){
$all_workers = array();
foreach($this->functions as $func=>$settings){
if(empty($settings["dedicated_only"])){
$all_workers[] = $func;
}
}
}
$worker_list = $all_workers;
} else {
$worker_list = array($worker);
}
$timeouts = array();
$default_timeout = ((isset($this->config['timeout'])) ?
(int) $this->config['timeout'] : null);
// build up the list of worker timeouts
foreach ($worker_list as $worker_name) {
$timeouts[$worker_name] = ((isset($this->config['functions'][$worker_name]['timeout'])) ?
(int) $this->config['functions'][$worker_name]['timeout'] : $default_timeout);
}
$pid = pcntl_fork();
switch($pid) {
case 0:
$this->isparent = false;
$this->register_ticks(false);
$this->pid = getmypid();
if(count($worker_list) > 1){
// shuffle the list to avoid queue preference
shuffle($worker_list);
// sort the shuffled array by priority
uasort($worker_list, array($this, "sort_priority"));
}
if($this->worker_restart_splay > 0){
$this->max_run_time = (int)rand($this->config['max_worker_lifetime'], $this->config['max_worker_lifetime'] + $this->worker_restart_splay);
$this->log("Adjusted max run time to $this->max_run_time seconds", GearmanManager::LOG_LEVEL_DEBUG);
}
$this->start_lib_worker($worker_list, $timeouts);
$this->log("Child exiting", GearmanManager::LOG_LEVEL_WORKER_INFO);
exit();
break;
case -1:
$this->log("Could not fork");
$this->stop_work = true;
$this->stop_children();
break;
default:
// parent
$this->log("Started child $pid (".implode(",", $worker_list).")", GearmanManager::LOG_LEVEL_PROC_INFO);
$this->children[$pid] = array(
"job" => $worker_list,
"start_time" => time(),
);
}
}
/**
* Sorts the function list by priority
*/
private function sort_priority($a, $b) {
$func_a = $this->functions[$a];
$func_b = $this->functions[$b];
if(!isset($func_a["priority"])){
$func_a["priority"] = 0;
}
if(!isset($func_b["priority"])){
$func_b["priority"] = 0;
}
if ($func_a["priority"] == $func_b["priority"]) {
return 0;
}
return ($func_a["priority"] > $func_b["priority"]) ? -1 : 1;
}
/**
* Stops all running children
*/
protected function stop_children($signal=SIGTERM) {
$this->log("Stopping children", GearmanManager::LOG_LEVEL_PROC_INFO);
foreach($this->children as $pid=>$child){
$this->log("Stopping child $pid (".implode(",", $child['job']).")", GearmanManager::LOG_LEVEL_PROC_INFO);
posix_kill($pid, $signal);
}
}
/**
* Registers the process signal listeners
*/
protected function register_ticks($parent=true) {
if($parent){
$this->log("Registering signals for parent", GearmanManager::LOG_LEVEL_DEBUG);
pcntl_signal(SIGTERM, array($this, "signal"));
pcntl_signal(SIGINT, array($this, "signal"));
pcntl_signal(SIGUSR1, array($this, "signal"));
pcntl_signal(SIGUSR2, array($this, "signal"));
pcntl_signal(SIGCONT, array($this, "signal"));
pcntl_signal(SIGHUP, array($this, "signal"));
} else {
$this->log("Registering signals for child", GearmanManager::LOG_LEVEL_DEBUG);
$res = pcntl_signal(SIGTERM, array($this, "signal"));
if(!$res){
exit();
}
}
}
/**