Test Failed
Push — test ( bcdd58...910c7a )
by Tom
02:33
created

StepRunner::obtainUserOptions()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 1
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 4
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Runner;
6
7
use Ktomk\Pipelines\Cli\Docker;
8
use Ktomk\Pipelines\DestructibleString;
9
use Ktomk\Pipelines\File\Pipeline\Step;
10
use Ktomk\Pipelines\Lib;
11
use Ktomk\Pipelines\LibFs;
12
use Ktomk\Pipelines\LibFsPath;
13
use Ktomk\Pipelines\LibTmp;
14
use Ktomk\Pipelines\Runner\Containers\StepContainer;
15
use Ktomk\Pipelines\Runner\Docker\ArtifactSource;
16
use Ktomk\Pipelines\Runner\Docker\Binary\Repository;
17
use Ktomk\Pipelines\Runner\Docker\ImageLogin;
18
19
/**
20
 * Runner for a single step of a pipeline
21
 */
22
class StepRunner
23
{
24
    /**
25
     * list of temporary directory destructible markers
26
     *
27
     * @var array
28
     */
29
    private $temporaryDirectories = array();
30
31
    /**
32
     * @var Runner
33
     */
34
    private $runner;
35
36
    /**
37
     * DockerSession constructor.
38
     *
39
     * @param Runner $runner
40
     */
41
    public function __construct(Runner $runner)
42
    {
43
        $this->runner = $runner;
44
    }
45
46
    /**
47
     * @param Step $step
48
     *
49
     * @return null|int exist status of step script or null if the run operation failed
50
     */
51
    public function runStep(Step $step)
52
    {
53
        $dir = $this->runner->getDirectories()->getProjectDirectory();
54
        $env = $this->runner->getEnv();
55
        $exec = $this->runner->getExec();
56
        $streams = $this->runner->getStreams();
57
58
        $containers = new Containers($this->runner);
59
60
        $env->setPipelinesProjectPath($dir);
61
62
        $container = $containers->createStepContainer($step);
63
64
        $env->setContainerName($container->getName());
65
66
        $image = $step->getImage();
67
68
        # launch container
69
        $streams->out(sprintf(
70
            "\x1D+++ step #%d\n\n    name...........: %s\n    effective-image: %s\n    container......: %s\n",
71
            $step->getIndex() + 1,
72 26
            $step->getName() ? '"' . $step->getName() . '"' : '(unnamed)',
73
            $image->getName(),
74
            $container->getName()
75
        ));
76
77
        $id = $container->keepOrKill();
78
79
        $deployCopy = $this->runner->getFlags()->deployCopy();
80
81 26
        if (null === $id) {
82 26
            list($id, $status, $out, $err) = $this->runNewContainer($container, $dir, $deployCopy, $step);
83 26
            if (null === $id) {
84 26
                $streams->out("    container-id...: *failure*\n\n");
85 26
                $streams->err("pipelines: setting up the container failed\n");
86 26
                empty($err) || $streams->err("${err}\n");
87 26
                empty($out) || $streams->out("${out}\n");
88
                $streams->out(sprintf("exit status: %d\n", $status));
89
90
                return $status;
91
            }
92
        }
93
94 25
        $streams->out(sprintf("    container-id...: %s\n\n", substr($id, 0, 12)));
95
96 25
        # TODO: different deployments, mount (default), mount-ro, copy
97 25
        if (null !== $result = $this->deployCopy($deployCopy, $id, $dir)) {
98 25
            $streams->err('pipelines: deploy copy failure\n');
99 25
100
            return $result;
101 25
        }
102
103 25
        $deployCopy && $streams('');
104
105 25
        $status = StepScriptRunner::createRunStepScript($step, $streams, $exec, $container->getName());
106 25
107 25
        $this->captureStepArtifacts($step, $deployCopy && 0 === $status, $id, $dir);
108
109 25
        $container->shutdown($status);
110
111 25
        return $status;
112
    }
113
114 25
    /**
115 25
     * method to wrap new to have a test-point
116 25
     *
117 25
     * @return Repository
118 25
     */
119
    public function getDockerBinaryRepository()
120
    {
121
        $repo = Repository::create($this->runner->getExec(), $this->runner->getDirectories());
122 25
        $repo->resolve($this->runner->getRunOpts()->getBinaryPackage());
123
124 25
        return $repo;
125
    }
126 25
127 23
    /**
128 22
     * @param Step $step
129 3
     * @param bool $copy
130
     * @param string $id container id
131
     * @param string $dir to put artifacts in (project directory)
132
     *
133 21
     * @throws \RuntimeException
134
     *
135
     * @return void
136 21
     */
137 2
    private function captureStepArtifacts(Step $step, $copy, $id, $dir)
138
    {
139
        # capturing artifacts is only supported for deploy copy
140 19
        if (!$copy) {
141
            return;
142 19
        }
143
144 19
        $artifacts = $step->getArtifacts();
145
146 19
        if (null === $artifacts) {
147
            return;
148 19
        }
149
150
        $exec = $this->runner->getExec();
151
        $streams = $this->runner->getStreams();
152
153
        $streams->out("\x1D+++ copying artifacts from container...\n");
154
155
        $source = new ArtifactSource($exec, $id, $dir);
156 2
157
        $patterns = $artifacts->getPatterns();
158 2
        foreach ($patterns as $pattern) {
159 2
            $this->captureArtifactPattern($source, $pattern, $dir);
160
        }
161 1
162
        $streams('');
163
    }
164
165
    /**
166
     * capture artifact pattern
167
     *
168
     * @param ArtifactSource $source
169
     * @param string $pattern
170
     * @param string $dir
171
     *
172
     * @throws \RuntimeException
173
     *
174 19
     * @return void
175
     *
176
     * @see Runner::captureStepArtifacts()
177 19
     *
178 14
     */
179
    private function captureArtifactPattern(ArtifactSource $source, $pattern, $dir)
180
    {
181 5
        $exec = $this->runner->getExec();
182
        $streams = $this->runner->getStreams();
183 5
184 2
        $id = $source->getId();
185
        $paths = $source->findByPattern($pattern);
186
        if (empty($paths)) {
187 3
            return;
188 3
        }
189
190 3
        $chunks = Lib::arrayChunkByStringLength($paths, 131072, 4);
191
192 3
        foreach ($chunks as $paths) {
193
            $docker = Lib::cmd('docker', array('exec', '-w', '/app', $id));
194 3
            $tar = Lib::cmd('tar', array('c', '-f', '-', $paths));
195 3
            $unTar = Lib::cmd('tar', array('x', '-f', '-', '-C', $dir));
196 3
197
            $command = $docker . ' ' . $tar . ' | ' . $unTar;
198
            $status = $exec->pass($command, array());
199 3
200 3
            if (0 !== $status) {
201
                $streams->err(sprintf(
202
                    "pipelines: Artifact failure: '%s' (%d, %d paths, %d bytes)\n",
203
                    $pattern,
204
                    $status,
205
                    count($paths),
206
                    strlen($command)
207
                ));
208
            }
209
        }
210
    }
211
212
    /**
213
     * @param bool $copy
214
     * @param string $id container id
215
     * @param string $dir directory to copy contents into container
216 3
     *
217
     * @throws \RuntimeException
218 3
     *
219 3
     * @return null|int null if all clear, integer for exit status
220
     */
221 3
    private function deployCopy($copy, $id, $dir)
222 3
    {
223 3
        if (!$copy) {
224 1
            return null;
225
        }
226
227 2
        $streams = $this->runner->getStreams();
228
        $exec = $this->runner->getExec();
229 2
230 2
        $streams->out("\x1D+++ copying files into container...\n");
231 2
232 2
        $tmpDir = LibTmp::tmpDir('pipelines-cp.');
233
        $this->temporaryDirectories[] = DestructibleString::rmDir($tmpDir);
234 2
        LibFs::symlink($dir, $tmpDir . '/app');
235 2
        $cd = Lib::cmd('cd', array($tmpDir . '/.'));
236
        $tar = Lib::cmd('tar', array('c', '-h', '-f', '-', '--no-recursion', 'app'));
237 2
        $dockerCp = Lib::cmd('docker ', array('cp', '-', $id . ':/.'));
238 1
        $status = $exec->pass("${cd} && echo 'app' | ${tar} | ${dockerCp}", array());
239 1
        LibFs::unlink($tmpDir . '/app');
240
        if (0 !== $status) {
241
            return $status;
242 1
        }
243 1
244
        $cd = Lib::cmd('cd', array($dir . '/.'));
245
        $tar = Lib::cmd('tar', array('c', '-f', '-', '.'));
246
        $dockerCp = Lib::cmd('docker ', array('cp', '-', $id . ':/app'));
247 2
        $status = $exec->pass("${cd} && ${tar} | ${dockerCp}", array());
248
        if (0 !== $status) {
249
            return $status;
250
        }
251
252
        return null;
253
    }
254
255
    /**
256
     * @param StepContainer $container
257
     * @param string $dir
258 21
     * @param bool $copy
259
     * @param Step $step
260 21
     *
261 14
     * @return array array(string|null $id, int $status, string $out, string $err)
262
     */
263
    private function runNewContainer(StepContainer $container, $dir, $copy, Step $step)
264 7
    {
265 7
        $env = $this->runner->getEnv();
266
267 7
        $mountDockerSock = $this->obtainDockerSocketMount();
268
269 7
        $mountDockerClient = $this->obtainDockerClientMount($step);
270 7
271 7
        $mountWorkingDirectory = $this->obtainWorkingDirMount($copy, $dir, $mountDockerSock);
272 7
        if ($mountWorkingDirectory && is_int($mountWorkingDirectory[1])) {
273 7
            return $mountWorkingDirectory + array(2 => '', 3 => '');
274 7
        }
275
276
        $network = $container->getServiceContainers()->obtainNetwork();
277 7
278 1
        # process docker login if image demands so, but continue on failure
279
        $image = $step->getImage();
280 1
        ImageLogin::loginImage($this->runner->getExec(), $this->runner->getEnv()->getResolver(), null, $image);
281
282
        list($status, $out, $err) = $container->run(
283 6
            array(
284 6
                $network,
285 6
                '-i', '--name', $container->getName(),
286 6
                $env->getArgs('-e'),
287 6
                $env::createArgVarDefinitions('-e', $step->getEnv()),
288 1
                $mountWorkingDirectory, '-e', 'BITBUCKET_CLONE_DIR=/app',
289
                $mountDockerSock,
290 1
                $mountDockerClient,
291
                $container->obtainUserOptions(),
292
                $container->obtainSshOptions(),
293 5
                '--workdir', '/app', '--detach', '--entrypoint=/bin/sh', $image->getName(),
294
            )
295 5
        );
296
        $id = $status ? null : $container->getDisplayId();
297
298
        return array($id, $status, $out, $err);
299
    }
300
301
    /**
302
     * @param Step $step
303
     *
304
     * @return string[]
305
     */
306
    private function obtainDockerClientMount(Step $step)
307
    {
308 23
        if (!$step->getServices()->has('docker')) {
309 23
            return array();
310
        }
311 23
312
        $path = $this->runner->getRunOpts()->getOption('docker.client.path');
313 23
314
        // prefer pip mount over package
315 22
        $hostPath = $this->pipHostConfigBind($path);
316 22
        if (null !== $hostPath) {
317 2
            return array('-v', sprintf('%s:%s:ro', $hostPath, $path));
318
        }
319
320 20
        $local = $this->getDockerBinaryRepository()->getBinaryPath();
321
        chmod($local, 0755);
322
323 20
        return array('-v', sprintf('%s:%s:ro', $local, $path));
324 20
    }
325
326 20
    /**
327
     * enable docker client inside docker by mounting docker socket
328 20
     *
329 20
     * @return array docker socket volume args for docker run, empty if not mounting
330 20
     */
331 20
    private function obtainDockerSocketMount()
332 20
    {
333 20
        $args = array();
334 20
335 20
        // FIXME give more controlling options, this is serious /!\
336
        if (!$this->runner->getFlags()->useDockerSocket()) {
337
            return $args;
338 20
        }
339 1
340 1
        $defaultSocketPath = $this->runner->getRunOpts()->getOption('docker.socket.path');
341 1
        $hostPathDockerSocket = $defaultSocketPath;
342 1
343 1
        // pipelines inside pipelines
344
        $hostPath = $this->pipHostConfigBind($defaultSocketPath);
345 1
        if (null !== $hostPath) {
346
            return array(
347 19
                '-v', sprintf('%s:%s', $hostPath, $defaultSocketPath),
348
            );
349 19
        }
350
351
        $dockerHost = $this->runner->getEnv()->getInheritValue('DOCKER_HOST');
352
        if (null !== $dockerHost && 0 === strpos($dockerHost, 'unix://')) {
353
            $hostPathDockerSocket = LibFsPath::normalize(substr($dockerHost, 7));
354
        }
355
356
        $pathDockerSock = $defaultSocketPath;
357
358
        if (file_exists($hostPathDockerSocket)) {
359 23
            $args = array(
360 20
                '-v', sprintf('%s:%s', $hostPathDockerSocket, $pathDockerSock),
361
            );
362
        }
363 3
364
        return $args;
365
    }
366 3
367 3
    /**
368 1
     * @param bool $copy
369
     * @param string $dir
370
     * @param array $mountDockerSock
371 2
     *
372 1
     * @return array mount options or array(null, int $status) for error handling
373
     */
374 1
    private function obtainWorkingDirMount($copy, $dir, array $mountDockerSock)
375
    {
376
        if ($copy) {
377
            return array();
378
        }
379
380
        $parentName = $this->runner->getEnv()->getValue('PIPELINES_PARENT_CONTAINER_NAME');
381
        $hostDeviceDir = $this->pipHostConfigBind($dir);
382
        $checkMount = $mountDockerSock && null !== $parentName;
383
        $deviceDir = $hostDeviceDir ?: $dir;
384 23
        if ($checkMount && '/app' === $dir && null === $hostDeviceDir) { // FIXME(tk): hard encoded /app
385
            $deviceDir = $this->runner->getEnv()->getValue('PIPELINES_PROJECT_PATH');
386
            if ($deviceDir === $dir || null === $deviceDir) {
387 23
                $this->runner->getStreams()->err("pipelines: fatal: can not detect ${dir} mount point\n");
388 1
389
                return array(null, 1);
390
            }
391 22
        }
392 22
393
        // FIXME(tk): Never mount anything not matching /home/[a-zA-Z][a-zA-Z0-9]*/[^.].*/...
394
        //   + do realpath checking
395 22
        //   + prevent dot path injections (logical fix first)
396 22
        return array('-v', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
397
    }
398 1
399
    /**
400
     * get host path from mount point if in pip level 2+
401
     *
402 21
     * @param mixed $mountPoint
403 21
     *
404 1
     * @return null|string
405
     */
406
    private function pipHostConfigBind($mountPoint)
407 21
    {
408
        // if there is a parent name, this is level 2+
409 21
        if (null === $pipName = $this->runner->getEnv()->getValue('PIPELINES_PIP_CONTAINER_NAME')) {
410
            return null;
411 18
        }
412
413
        return Docker::create($this->runner->getExec())->hostConfigBind($pipName, $mountPoint);
414
    }
415
}
416