|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* this file is part of pipelines */ |
|
4
|
|
|
|
|
5
|
|
|
namespace Ktomk\Pipelines\Cli; |
|
6
|
|
|
|
|
7
|
|
|
use Ktomk\Pipelines\Lib; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Process manager for docker container |
|
11
|
|
|
*/ |
|
12
|
|
|
class DockerProcessManager |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var Exec |
|
16
|
|
|
*/ |
|
17
|
|
|
private $exec; |
|
18
|
|
|
|
|
19
|
6 |
|
public function __construct(Exec $exec = null) |
|
20
|
|
|
{ |
|
21
|
6 |
|
if (null === $exec) { |
|
22
|
1 |
|
$exec = new Exec(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
6 |
|
$this->exec = $exec; |
|
26
|
6 |
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* container ids by name prefix of running and stopped containers |
|
30
|
|
|
* |
|
31
|
|
|
* @param string $prefix |
|
32
|
|
|
* @return null|array of ids, null if an internal error occurred |
|
33
|
|
|
*/ |
|
34
|
2 |
|
public function findAllContainerIdsByNamePrefix($prefix) |
|
35
|
|
|
{ |
|
36
|
2 |
|
return $this->psPrefixImpl($prefix, true); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* container ids by name prefix of running containers |
|
41
|
|
|
* |
|
42
|
|
|
* @param string $prefix |
|
43
|
|
|
* @return null|array of ids, null if an internal error occurred |
|
44
|
|
|
*/ |
|
45
|
1 |
|
public function findRunningContainerIdsByNamePrefix($prefix) |
|
46
|
|
|
{ |
|
47
|
1 |
|
return $this->psPrefixImpl($prefix); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param string|string[] $idOrIds |
|
52
|
|
|
* @return int |
|
53
|
|
|
*/ |
|
54
|
1 |
|
public function kill($idOrIds) |
|
55
|
|
|
{ |
|
56
|
1 |
|
return $this->exec->capture('docker', Lib::merge('kill', func_get_args())); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param string|string[] $idOrIds |
|
61
|
|
|
* @return int |
|
62
|
|
|
*/ |
|
63
|
1 |
|
public function remove($idOrIds) |
|
64
|
|
|
{ |
|
65
|
1 |
|
return $this->exec->capture('docker', Lib::merge('rm', func_get_args())); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param string $prefix |
|
70
|
|
|
* @param bool $all |
|
71
|
|
|
* @return null|array |
|
72
|
|
|
*/ |
|
73
|
3 |
|
private function psPrefixImpl($prefix, $all = false) |
|
74
|
|
|
{ |
|
75
|
3 |
|
$ids = null; |
|
76
|
|
|
|
|
77
|
3 |
|
if (0 === preg_match('(^[a-zA-Z0-9][a-zA-Z0-9_.-]+$)', $prefix)) { |
|
78
|
1 |
|
throw new \InvalidArgumentException( |
|
79
|
1 |
|
sprintf('Invalid container name prefix "%s"', $prefix) |
|
80
|
|
|
); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
2 |
|
$status = $this->exec->capture( |
|
84
|
2 |
|
'docker', |
|
85
|
|
|
array( |
|
86
|
2 |
|
'ps', '-q' . ($all ? 'a' : ''), '--no-trunc', '--filter', |
|
87
|
2 |
|
"name=^/${prefix}" |
|
88
|
|
|
), |
|
89
|
|
|
$result |
|
90
|
|
|
); |
|
91
|
|
|
|
|
92
|
|
|
$status || $ids = Lib::lines($result); |
|
93
|
|
|
|
|
94
|
|
|
return $ids; |
|
95
|
|
|
} |
|
96
|
|
|
} |
|
97
|
|
|
|