Passed
Push — test ( e1582a...df0fbb )
by Tom
08:14
created

StepRunner::obtainDockerClientMount()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

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

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
431 12
        $deviceDir = $hostDeviceDir ?: $dir;
432 12
        if ($checkMount && '/app' === $dir && null === $hostDeviceDir) { // FIXME(tk): hard encoded /app
433 2
            $deviceDir = $this->env->getPipelinesProjectPath($deviceDir);
434 2
            if ($deviceDir === $dir || null === $deviceDir) {
435 2
                $this->streams->err("pipelines: fatal: can not detect ${dir} mount point. preventing new container.\n");
436
437 2
                return array(null, 1);
438
            }
439
        }
440
441
        // FIXME(tk): Never mount anything not matching /home/[a-zA-Z][a-zA-Z0-9]*/[^.].*/...
442
        //   + do realpath checking
443
        //   + prevent dot path injections (logical fix first)
444 10
        return array('-v', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
445
    }
446
447
    /**
448
     * get host path from mount point if in pip level 2+
449
     *
450
     * @param mixed $mountPoint
451
     * @return null|string
452
     */
453
    private function pipHostConfigBind($mountPoint)
454
    {
455
        // if there is a parent name, this is level 2+
456 20
        if (null === $this->env->getValue('PIPELINES_PARENT_CONTAINER_NAME')) {
457 15
            return null;
458
        }
459
460 5
        if (null === $pipName = $this->env->getValue('PIPELINES_PIP_CONTAINER_NAME')) {
461 2
            return null;
462
        }
463
464 3
        return Docker::create($this->exec)->hostConfigBind($pipName, $mountPoint);
465
    }
466
467
    /**
468
     * @param Step $step
469
     * @param Streams $streams
470
     * @param Exec $exec
471
     * @param string $name container name
472
     *
473
     * @return null|int should never be null, status, non-zero if a command failed
474
     */
475
    private function runStepScript(Step $step, Streams $streams, Exec $exec, $name)
476
    {
477 16
        $script = $step->getScript();
478
479 16
        $buffer = Lib::cmd("<<'SCRIPT' docker", array(
480 16
            'exec', '-i', $name, '/bin/sh',
481
        ));
482 16
        $buffer .= "\n# this /bin/sh script is generated from a pipelines pipeline:\n";
483 16
        $buffer .= "set -e\n";
484 16
        foreach ($script as $line => $command) {
485 16
            $line && $buffer .= 'printf \'\\n\'' . "\n";
486 16
            $buffer .= 'printf \'\\035+ %s\\n\' ' . Lib::quoteArg($command) . "\n";
487 16
            $buffer .= $command . "\n";
488
        }
489 16
        $buffer .= "SCRIPT\n";
490
491 16
        $status = $exec->pass($buffer, array());
492
493 16
        if (0 !== $status) {
494 2
            $streams->err(sprintf("script non-zero exit status: %d\n", $status));
495
        }
496
497 16
        return $status;
498
    }
499
500
    /**
501
     * @param StepContainer $container
502
     * @param int $status
503
     */
504
    private function shutdownStepContainer(StepContainer $container, $status)
505
    {
506 16
        $flags = $this->flags;
507 16
        $id = $container->getDisplayId();
508
509
        # keep container on error
510 16
        if (0 !== $status && $flags->keepOnError()) {
511 2
            $this->streams->err(sprintf(
512 2
                "error, keeping container id %s\n",
513 2
                substr($id, 0, 12)
514
            ));
515
516 2
            return;
517
        }
518
519
        # keep or kill/remove container
520 14
        $container->killAndRemove($flags->killContainer(), $flags->removeContainer());
521
522 14
        if ($flags->keep()) {
523 1
            $this->streams->out(sprintf(
524 1
                "keeping container id %s\n",
525 1
                substr($id, 0, 12)
526
            ));
527
        }
528 14
    }
529
}
530