forked from clue/reactphp-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec-stream.php
61 lines (46 loc) · 1.71 KB
/
exec-stream.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
<?php
// this example executes some commands within the given running container and
// displays the streaming output as it happens.
use Clue\React\Docker\Client;
use React\Stream\WritableResourceStream;
require __DIR__ . '/../vendor/autoload.php';
if (DIRECTORY_SEPARATOR === '\\') {
exit('File I/O not supported on Windows' . PHP_EOL);
}
$container = 'asd';
//$cmd = array('echo', 'hello world');
//$cmd = array('sleep', '2');
$cmd = array('sh', '-c', 'echo -n hello && sleep 1 && echo world && sleep 1 && env');
//$cmd = array('cat', 'invalid-path');
if (isset($argv[1])) {
$container = $argv[1];
$cmd = array_slice($argv, 2);
}
$loop = React\EventLoop\Factory::create();
$client = new Client($loop);
$out = new WritableResourceStream(STDOUT, $loop);
$stderr = new WritableResourceStream(STDERR, $loop);
// unkown exit code by default
$exit = 1;
$client->execCreate($container, $cmd)->then(function ($info) use ($client, $out, $stderr, &$exit) {
$stream = $client->execStartStream($info['Id'], false, 'stderr');
$stream->pipe($out);
// forward custom stderr event to STDERR stream
$stream->on('stderr', function ($data) use ($stderr, $stream) {
if ($stderr->write($data) === false) {
$stream->pause();
$stderr->once('drain', function () use ($stream) {
$stream->resume();
});
}
});
$stream->on('error', 'printf');
// remember exit code of executed command once it closes
$stream->on('close', function () use ($client, $info, &$exit) {
$client->execInspect($info['Id'])->then(function ($info) use (&$exit) {
$exit = $info['ExitCode'];
}, 'printf');
});
}, 'printf');
$loop->run();
exit($exit);