-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAsynchronousCommand.php
More file actions
executable file
·721 lines (523 loc) · 24.1 KB
/
AsynchronousCommand.php
File metadata and controls
executable file
·721 lines (523 loc) · 24.1 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
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
<?php
/************************************************************************************************************
NAME
AsynchronousCommand.phpclass
DESCRIPTION
This class addresses the case where an external command is to be run, and its output needs to be
captured and interpreted as soon as the external command emits it.
It uses streams to pipe standard output of the child process and be able to read it.
Unfortunately for Windows users, there are several limitations that this class tries to overcome :
- The stream_set_blocking() PHP function does not work, due to a Windows limitation. Thus, a call to
fread() on whichever pipe that has been established will be a blocking call.
- There was an alternative of using stream_select(), which returns the pipes/sockets on which new
events are available. However, the select() Windows API used on streams that are not yet available
returns the stream descriptors themselves as if new data was available on them.
The consequence is that a call to fread() on one of these streams which is in a "non-available"
state will be blocking.
For these reasons, on Windows it is currently impossible to separately get in PHP the output
generated by a child process on both stdout and stderr without eventually doing a blocking call.
For those reasons, this class makes a compromise : you can spawn a child process, send data to it
through its stdin file descriptor, read from its standard output, but you will not be able to
differentiate between stdout and stderr. Both will be mixed because stderr will systematically be
redirected to stdout.
Listed below is an example of how to run a command, capture in real-time its standard output, and do
some special processing if a given string is encountered in the child output :
$cmd = new AsynchronousCommand ( "somecommand" ) ;
$cmd -> Run ( ) ;
echo ( "Execute pid = " . $cmd -> GetPid ( ) . "\n" ) ;
while ( $cmd -> IsRunning ( ) )
{
while ( ( $data = $cmd -> ReadLine ( ) ) !== false )
{
echo ( "$data\n" ) ;
if ( strpos ( $data, "some string value that makes me stop" ) !== false )
{
$cmd -> Terminate ( ) ; // Terminate the child process
break ;
}
}
}
$cmd -> Terminate ( ) ;
output ( "Finished, exit code = " . $cmd -> GetExitCode ( ) ) ;
It is also possible to write to the child process standard input ; for that, just instanciate the
command object using "true" as the second parameter ($pipe_stdin) :
$cmd = new AsynchronousCommand ( "somecommand", true ) ;
Then, in the while loop, add the following code to write something if an input request has been made :
if ( $cmd -> IsStdinRequested ( ) )
$cmd -> WriteLine ( "my output for my somecommand command" ) ;
AUTHOR
Christian Vigh, 11/2014.
HISTORY
[Version : 1.0] [Date : 2014/11/20] [Author : CV]
Initial version.
[Version : 1.0.1] [Date : 2014/12/09] [Author : CV]
. Added the Execute static function.
[Version : 1.0.2] [Date : 2014/12/15] [Author : CV]
. Added the $cwd parameter to the Execute() static function.
[Version : 1.0.3] [Date : 2015/02/06] [Author : CV]
. Corrected a bug : for the caller, the PollTimeout value is expressed in milliseconds. However,
timeouts passed to the streams api are to be expressed in microseconds. Thus, the PollTimeout value
must be multiplied by 1000, which was not the case.
. The ReadLine() function did not return false upon EOF.
. Use stream_get_line() insted of fread/fgets.
[Version : 1.0.4] [Date : 2015/06/10] [Author : CV]
. Added the BackgroundCommand class, which allows for launching a command in background without taking
care of its standard input/output descriptors.
************************************************************************************************************/
// Determine if we run under Windows or Unix
if ( ! strncasecmp ( php_uname ( 's' ), 'windows', 7 ) )
{
define ( 'IS_WINDOWS' , 1 ) ;
define ( 'IS_UNIX' , 0 ) ;
}
else
{
define ( 'IS_WINDOWS' , 0 ) ;
define ( 'IS_UNIX' , 1 ) ;
}
/*===========================================================================================================
AynchronousCommand class -
Allows for asynchronous command execution and real-time output retrieval.
===========================================================================================================*/
class AsynchronousCommand
{
// The command to be run
protected $Command ;
// Its working directory - null means "current"
protected $Cwd = null ;
// Its environment variables - null means "use defined environment variables"
protected $Environment = null ;
// An timeout in milliseconds where stdout streams are to be checked for the presence of data
protected $PollTimeout = 1000 ;
// A flag indicating whether stdin should be the same for the child process as it is for its parent
// process (false). Specify true if you want to write to the child standard input using the Write()
// or WriteLine() methods.
protected $PipeStdin ;
// Descriptors for proc_open()
protected $Descriptors ;
// Output pipes from proc_open()
protected $Pipes ;
// Child process execution status
protected $Status ;
/*===========================================================================================================
NAME
Constructor - Starts a child process.
PROTOTYPE
$cmd = new AsynchronousCommand ( $command, $pipe_stdin = false, $run = false ) ;
DESCRIPTION
Creates a child process using the specified command.
PARAMETERS
$command (string) -
Command to be executed.
$pipe_stdin (boolean) -
When true, the parent process (ie, the one that instanciated an AsynchronousCommand object)
will be able to write to its child stdin file descriptor using the Write or WriteLine methods.
When false (the default), the file descriptor used for the child's standard input is the one
of the parent process.
$run (boolean) -
When true, the command is run immediately.
NOTES
Due to the current limitations of Windows and PHP Windows, only the child process standard output can
be read from a pipe as a non-blocking call. The child standard error is always redirected to standard
output.
===========================================================================================================*/
public function __construct ( $command, $pipe_stdin = false, $run = false )
{
// Analyze the command to redirect its standard error.
$this -> Command = $this -> RedirectStderr ( $command ) ;
// Initialize file descriptors/
$this -> Descriptors =
[
0 => ( $pipe_stdin ) ? [ "pipe", "r" ] : STDIN,
1 => [ "pipe", "w" ]
] ;
$this -> PipeStdin = $pipe_stdin ;
$this -> Status = false ;
// Run the command if requested.
if ( $run )
$this -> Run ( ) ;
}
/*===========================================================================================================
RedirectStderr -
Analyzes the specified command to redirect its standard error.
===========================================================================================================*/
protected function RedirectStderr ( $command )
{
static $re = '#
(
["]
( [^"] | \\\\["] ) *
["]
)
|
(
[\']
( [^\'] | \\\\ [\'] ) *
[\']
)
|
( \\\\ [|&] )
#imsx' ;
// First, ignore any quoted strings and any escaped character than can be used in a pipe or command chaining construct
$str = preg_replace ( $re, '', trim ( $command ) ) ;
// Then split the string based on allowed shell pipe constructs
$str = str_replace ( [ '||', '&&', '|' ], chr ( 1 ), $str ) ;
$parts = explode ( chr ( 1 ), $str ) ;
$last = $parts [ count ( $parts ) - 1 ] ;
// If no stderr redirection exists, add ours
if ( strpos ( $last, "2>" ) === false )
$command .= " 2>&1" ;
return ( $command ) ;
}
/*===========================================================================================================
Shutdown -
Terminates the child process.
On Windows platform, the $signal parameter is ignored since an external Windows command, TASKKILL, is
used to terminate the process (proc_terminate does not kill child process, which leaves zombie PHP
interpreters consuming all the CPU when the command is terminated).
===========================================================================================================*/
protected function Shutdown ( $signal = 15 )
{
if ( $this -> Process )
{
// Get current child process status
$this -> UpdateStatus ( ) ;
// Close all the opened pipes, otherwise process_close() will block
fclose ( $this -> Pipes [1] ) ;
if ( $this -> PipeStdin ) // This is also true if stdin has been piped
fclose ( $this -> Pipes [0] ) ;
// Kill the child process if it is still running
if ( $this -> Status [ 'running' ] )
{
if ( IS_WINDOWS )
exec ( "TASKKILL /F /T /PID {$this -> Status [ 'pid' ]} >NUL: 2>&1" ) ;
else
proc_terminate ( $this -> Process, $signal ) ;
}
// Udate once again the status, mainly to get the child process exit code
$this -> UpdateStatus ( ) ;
// Close the child process
proc_close ( $this -> Process ) ;
}
$this -> Process = false ;
}
/*===========================================================================================================
UpdateStatus -
Updates the internal status of the running child process.
===========================================================================================================*/
protected function UpdateStatus ( )
{
if ( ! $this -> Process )
throw ( new \RuntimeException ( "No process to get status from." ) ) ;
$this -> Status = proc_get_status ( $this -> Process ) ;
}
/*==============================================================================================================
NAME
Execute - Executes a command.
PROTOTYPE
$status = AsynchronousCommand::Execute ( $command, $cwd = null, $callback = null,
$line_buffering = true ) ;
DESCRIPTION
A shortcut for executing a command and displaying its output onto standard output.
A callback can be specified to handle each chunk of output.
PARAMETERS
$command (string) -
Command to execute.
$cwd (string) -
Current directory for command execution.
$callback (callback) -
Function that will be called for processing each chunk of data read from the command output
stream. The callback must have the following signature :
boolean callback ( $data ) ;
The data will be written to standard output if the callback returns false.
$line_buffering (boolean) -
When true (the default), the command output stream data will be read line by line.
RETURN VALUE
Returns the command exit status.
==============================================================================================================*/
public static function Execute ( $command, $cwd = null, $callback = null, $line_buffering = true )
{
$cmd = new AsynchronousCommand ( $command, false ) ;
if ( $cwd )
$cmd -> SetCwd ( $cwd ) ;
$readfunc = ( $line_buffering ) ? 'ReadLine' : 'Read' ;
$cmd -> Run ( ) ;
while ( $cmd -> IsRunning ( ) )
{
if ( ( $data = $cmd -> $readfunc ( ) ) != false )
{
if ( $callback )
$status = $callback ( $data ) ;
else
$status = false ;
if ( ! $status )
echo ( $data ) ;
}
}
$cmd -> Terminate ( ) ;
return ( $cmd -> Status ) ;
}
/*===========================================================================================================
Various getters.
===========================================================================================================*/
// Get the command to run
public function GetCommand ( )
{ return ( $this -> Command ) ; }
// Get the command current directory (specified before running it...)
public function GetCwd ( )
{ return ( $this -> Cwd ) ; }
// Get the command environment variables (specified before running it...)
public function GetEnvironment ( )
{ return ( $this -> Environment ) ; }
// Get the command exit code (only available when terminated, otherwise -1)
public function GetExitCode ( )
{ return ( $this -> Status [ 'exitcode' ] ) ; }
// Get the command pid
public function GetPid ( )
{ return ( $this -> Status [ 'pid' ] ) ; }
// Get the timeout in microseconds when checking if data is available on the stdout pipe
public function GetPollTimeout ( )
{ return ( $this -> PollTimeout ) ; }
// For terminated processes, get the signal number that was sent (0 = not killed)
public function GetTerminationSignal ( )
{ return ( $this -> Status [ 'termsig' ] ) ; }
// For stopped process, get the signal number that stopped them
public function GetStopSignal ( )
{ return ( $this -> Status [ 'stopsig' ] ) ; }
// Returns a flag indicating if the child process received a signal.
public function IsSignaled ( )
{ return ( $this -> Status [ 'signaled' ] ) ; }
// Returns a flag indicating if the child process standard input was piped to the parent process standard output
public function IsStdinPiped ( )
{ return ( $this -> PipeStdin ) ; }
// Returns a flag indicating if the child process was stopped.
public function IsStopped ( )
{ return ( $this -> Status [ 'stopped' ] ) ; }
/*===========================================================================================================
NAME
GetStdin - Gets the child process descriptor for standard input.
PROTOTYPE
$fd = $cmd -> GetStdin ( ) ;
DESCRIPTION
Gets the file descriptor for the standard input of the child process.
RETURN VALUE
A file descriptor (either a pipe or the standard output of the parent process).
===========================================================================================================*/
public function GetStdin ( )
{
if ( ! $this -> Process )
throw ( new \RuntimeException ( "No process running." ) ) ;
if ( $this -> StdinPiped )
return ( $this -> pipes [0] ) ;
else
return ( STDIN ) ;
}
/*===========================================================================================================
NAME
GetStdout - Returns the standard output file descriptor of a child process.
PROTOTYPE
$fd = $cmd -> GetStdout ( ) ;
DESCRIPTION
Returns the file descriptor for the standard output of the child process.
RETURN VALUE
A file descriptor (this is always the descriptor of a pipe).
===========================================================================================================*/
public function GetStdout ( )
{
if ( ! $this -> Process )
throw ( new \RuntimeException ( "No process running." ) ) ;
return ( $this -> Pipes [1] ) ;
}
/*===========================================================================================================
NAME
IsRunning - Checks if the command is running.
PROTOTYPE
$bool = $cmd -> IsRunning ( ) ;
DESCRIPTION
Checks if the command is still running.
RETURN VALUE
False if the process has not been started or has been terminated, true otherwise.
===========================================================================================================*/
public function IsRunning ( )
{
if ( ! $this -> Process )
return ( false ) ;
// Make sure we always have an up-to-date status
$this -> UpdateStatus ( ) ;
$running = $this -> Status [ 'running' ] ;
// if not running, ensure that all things were properly shut down
if ( ! $running )
$this -> Shutdown ( ) ;
return ( $running ) ;
}
/*===========================================================================================================
NAME
IsStdinRequested - Checks if the child process is requesting for input.
PROTOTYPE
$bool = $cmd -> IsStdinRequested ( ) ;
DESCRIPTION
Checks if the next call to Write/WriteLine will be blocking or not.
RETURN VALUE
false if the next write will be blocking, true otherwise.
NOTES
The stream_select() function is called, so that IsStdinRequested() will be a non-blocking call.
===========================================================================================================*/
public function IsStdinRequested ( )
{
if ( ! $this -> PipeStdin )
return ( false ) ;
$readable = [] ;
$writable = [ $this -> Pipes [0] ] ;
$exceptions = [] ;
$status = stream_select ( $readable, $writable, $exceptions, 0, $this -> PollTimeout * 1000 ) ;
if ( $status )
return ( true ) ;
else
return ( false ) ;
}
/*===========================================================================================================
NAME
IsStdoutAvailable - Checks if data is available on child process standard output.
PROTOTYPE
$bool = $cmd -> IsStdoutAvailable ( ) ;
DESCRIPTION
This function checks if data is available on the child process standard output.
If this is the case, it can be read using the Read or ReadLine methods.
NOTES
The stream_select() function is called, so that IsStdoutAvailable() will be a non-blocking call.
===========================================================================================================*/
public function IsStdoutDataAvailable ( )
{
$readable = [ $this -> Pipes [1] ] ;
$writable = [] ;
$exceptions = [] ;
$status = stream_select ( $readable, $writable, $exceptions, 0, $this -> PollTimeout * 1000 ) ;
if ( $status )
return ( true ) ;
else
return ( false ) ;
}
/*===========================================================================================================
Some settings to be defined before calling the Run() method.
===========================================================================================================*/
// Sets the child process working directory
public function SetCwd ( $cwd )
{ $this -> Cwd = $cwd ; }
// Sets the poll timeout value (in microseconds). The effect of this function is immediate, it can be safely
// called from within a while ( IsRunning() ) loop.
public function SetPollTimeout ( $interval )
{ $this -> PollTimeout = $interval ; }
// Set the child process environment variables
public function SetEnvironment ( $env )
{ $this -> Environment = $env ; }
/*===========================================================================================================
NAME
Read, ReadLine - Reads data from the child standard output.
PROTOTYPE
$data = $cmd -> Read ( ) ;
$data = $cmd -> ReadLine ( ) ;
DESCRIPTION
Read() reads data from the child process standard output, up to 8Kb.
ReadLine() reads a line, until an end of line is met.
RETURN VALUE
The data read from the child process standard output.
For ReadLine(), the trailing newline is stripped from the returned value.
===========================================================================================================*/
public function Read ( )
{
if ( $this -> IsStdoutDataAvailable ( ) )
return ( stream_get_line ( $this -> Pipes [1], 8192 ) ) ;
else
return ( false ) ;
}
public function ReadLine ( )
{
$status = $this -> IsStdoutDataAvailable ( ) ;
$result = false ;
if ( $status )
{
$line = stream_get_line ( $this -> Pipes [1], 8192, "\n" ) ;
if ( $line !== false )
$result = rtrim ( $line ) ;
}
return ( $result ) ;
}
/*===========================================================================================================
NAME
Run - Runs the command specified on the AsynchronousCommand constructor.
PROTOTYPE
$cmd -> Run ( ) ;
DESCRIPTION
Runs the command specified on the AsynchronousCommand constructor.
Output pipes are set to non-blocking (except on Windows platforms=.
===========================================================================================================*/
public function Run ( )
{
$pipes = null ;
$this -> Process = proc_open ( $this -> Command, $this -> Descriptors, $this -> Pipes,
$this -> Cwd, $this -> Environment ) ;
if ( $this -> Process === false )
throw ( new \RuntimeException ( "Unable to start process." ) ) ;
// Useless on Windows :
stream_set_blocking ( $this -> Pipes [1], 1 ) ;
// Update current status to reflect the state of this new process
$this -> UpdateStatus ( $this -> Process ) ;
}
/*===========================================================================================================
NAME
Terminate - Terminates the currently executing process.
PROTOTYPE
$cmd -> Terminate ( $signal = 15 ) ;
DESCRIPTION
Terminates the currently executing process.
PARAMETERS
$signal (integer) -
(Unix systems only) Signal to be sent to the running process.
===========================================================================================================*/
public function Terminate ( $signal = 15 )
{
if ( $this -> Process )
$this -> Shutdown ( $signal ) ;
}
/*===========================================================================================================
NAME
Write, WriteLine - Writes to the child process standard input.
PROTOTYPE
$cmd -> Write ( $str [, $length ] ) ;
$cmd -> WriteLine ( $str ) ;
DESCRIPTION
Writes data to the standard input of the child process.
This only works when the $pipe_stdin of the class constructor has been set to true.
===========================================================================================================*/
public function Write ( $str, $length = false )
{
if ( ! $this -> PipeStdin )
throw ( new \RuntimeException ( "Cannot write to child process standard input : STDIN was not piped." ) ) ;
if ( $length !== false )
fwrite ( $this -> Pipes [0], $str, $length ) ;
else
fwrite ( $this -> Pipes [0], $str ) ;
}
public function WriteLine ( $str )
{
if ( ! $this -> PipeStdin )
throw ( new \RuntimeException ( "Cannot write to child process standard input : STDIN was not piped." ) ) ;
fwrite ( $this -> Pipes [0], $str . PHP_EOL ) ;
}
}
/*==============================================================================================================
BackgroundCommand -
A class for commands to be run in background.
==============================================================================================================*/
class BackgroundCommand
{
public function __construct ( )
{
parent::__construct ( ) ;
}
public static function Run ( $command )
{
$cmd = new AsynchronousCommand ( $command ) ;
$cmd -> Run ( ) ;
}
}