Passed
Push — test ( 4c4f16...57c681 )
by Tom
02:51
created

StepRunner::pipHostConfigBind()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 3
rs 10
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($this->runOpts->getPrefix(), $this->directories->getName());
106 22
        $env->setContainerName($name);
107
108 22
        $image = $step->getImage();
109
110
        # launch container
111 22
        $streams->out(sprintf(
112 22
            "\x1D+++ step #%d\n\n    name...........: %s\n    effective-image: %s\n    container......: %s\n",
113 22
            $step->getIndex() + 1,
114 22
            $step->getName() ? '"' . $step->getName() . '"' : '(unnamed)',
115 22
            $image->getName(),
116 22
            $name
117
        ));
118
119 22
        $id = $container->keepOrKill($this->flags->reuseContainer());
120
121 22
        $deployCopy = $this->flags->deployCopy();
122
123 22
        if (null === $id) {
124 20
            list($id, $status) = $this->runNewContainer($container, $dir, $deployCopy, $step);
125 20
            if (null === $id) {
126 3
                return $status;
127
            }
128
        }
129
130 19
        $streams->out(sprintf("    container-id...: %s\n\n", substr($id, 0, 12)));
131
132
        # TODO: different deployments, mount (default), mount-ro, copy
133 19
        if (null !== $result = $this->deployCopy($deployCopy, $id, $dir)) {
134 2
            return $result;
135
        }
136
137 17
        list($status, $message) = $this->deployDockerClient($step, $id);
138 16
        if (0 !== $status) {
139 1
            $this->streams->err(rtrim($message, "\n") . "\n");
140
141 1
            return $status;
142
        }
143
144 15
        $status = $this->runStepScript($step, $streams, $exec, $name);
145
146 15
        $this->captureStepArtifacts($step, $deployCopy && 0 === $status, $id, $dir);
147
148 15
        $this->shutdownStepContainer($container, $status);
149
150 15
        return $status;
151
    }
152
153
    /**
154
     * method to wrap new to have a test-point
155
     *
156
     * @return Repository
157
     */
158 2
    public function getDockerBinaryRepository()
159
    {
160 2
        $repo = Repository::create($this->exec, $this->directories);
161 2
        $repo->resolve($this->runOpts->getBinaryPackage());
162
163 1
        return $repo;
164
    }
165
166
    /**
167
     * @param Step $step
168
     * @param bool $copy
169
     * @param string $id container id
170
     * @param string $dir to put artifacts in (project directory)
171
     *
172
     * @throws \RuntimeException
173
     */
174 15
    private function captureStepArtifacts(Step $step, $copy, $id, $dir)
175
    {
176
        # capturing artifacts is only supported for deploy copy
177 15
        if (!$copy) {
178 10
            return;
179
        }
180
181 5
        $artifacts = $step->getArtifacts();
182
183 5
        if (null === $artifacts) {
184 2
            return;
185
        }
186
187 3
        $exec = $this->exec;
188 3
        $streams = $this->streams;
189
190 3
        $streams->out("\x1D+++ copying artifacts from container...\n");
191
192 3
        $source = new ArtifactSource($exec, $id, $dir);
193
194 3
        $patterns = $artifacts->getPatterns();
195 3
        foreach ($patterns as $pattern) {
196 3
            $this->captureArtifactPattern($source, $pattern, $dir);
197
        }
198
199 3
        $streams('');
200 3
    }
201
202
    /**
203
     * @param ArtifactSource $source
204
     * @param string $pattern
205
     * @param string $dir
206
     *
207
     * @throws \RuntimeException
208
     * @see Runner::captureStepArtifacts()
209
     *
210
     */
211 3
    private function captureArtifactPattern(ArtifactSource $source, $pattern, $dir)
212
    {
213 3
        $exec = $this->exec;
214 3
        $streams = $this->streams;
215
216 3
        $id = $source->getId();
217 3
        $paths = $source->findByPattern($pattern);
218 3
        if (empty($paths)) {
219 1
            return;
220
        }
221
222 2
        $chunks = Lib::arrayChunkByStringLength($paths, 131072, 4);
223
224 2
        foreach ($chunks as $paths) {
225 2
            $docker = Lib::cmd('docker', array('exec', '-w', '/app', $id));
226 2
            $tar = Lib::cmd('tar', array('c', '-f', '-', $paths));
227 2
            $unTar = Lib::cmd('tar', array('x', '-f', '-', '-C', $dir));
228
229 2
            $command = $docker . ' ' . $tar . ' | ' . $unTar;
230 2
            $status = $exec->pass($command, array());
231
232 2
            if (0 !== $status) {
233 1
                $streams->err(sprintf(
234 1
                    "pipelines: Artifact failure: '%s' (%d, %d paths, %d bytes)\n",
235 1
                    $pattern,
236 1
                    $status,
237 1
                    count($paths),
238 1
                    strlen($command)
239
                ));
240
            }
241
        }
242 2
    }
243
244
    /**
245
     * @param bool $copy
246
     * @param string $id container id
247
     * @param string $dir directory to copy contents into container
248
     *
249
     * @throws \RuntimeException
250
     * @return null|int null if all clear, integer for exit status
251
     */
252 19
    private function deployCopy($copy, $id, $dir)
253
    {
254 19
        if (!$copy) {
255 12
            return null;
256
        }
257
258 7
        $streams = $this->streams;
259 7
        $exec = $this->exec;
260
261 7
        $streams->out("\x1D+++ copying files into container...\n");
262
263 7
        $tmpDir = LibTmp::tmpDir('pipelines-cp.');
264 7
        $this->temporaryDirectories[] = DestructibleString::rmDir($tmpDir);
265 7
        LibFs::symlink($dir, $tmpDir . '/app');
266 7
        $cd = Lib::cmd('cd', array($tmpDir . '/.'));
267 7
        $tar = Lib::cmd('tar', array('c', '-h', '-f', '-', '--no-recursion', 'app'));
268 7
        $dockerCp = Lib::cmd('docker ', array('cp', '-', $id . ':/.'));
269
        $status = $exec->pass("${cd} && echo 'app' | ${tar} | ${dockerCp}", array());
270
        LibFs::unlink($tmpDir . '/app');
271 7
        if (0 !== $status) {
272 1
            $streams->err('pipelines: deploy copy failure\n');
273
274 1
            return $status;
275
        }
276
277 6
        $cd = Lib::cmd('cd', array($dir . '/.'));
278 6
        $tar = Lib::cmd('tar', array('c', '-f', '-', '.'));
279 6
        $dockerCp = Lib::cmd('docker ', array('cp', '-', $id . ':/app'));
280 6
        $status = $exec->pass("${cd} && ${tar} | ${dockerCp}", array());
281 6
        if (0 !== $status) {
282 1
            $streams->err('pipelines: deploy copy failure\n');
283
284 1
            return $status;
285
        }
286
287 5
        $streams('');
288
289 5
        return null;
290
    }
291
292
    /**
293
     * if there is the docker service in the step, deploy the
294
     * docker client
295
     *
296
     * @param Step $step
297
     * @param string $id
298
     *
299
     * @throws
300
     * @return array array(int $status, string $message)
301
     */
302
    private function deployDockerClient(Step $step, $id)
303
    {
304 17
        if (!$step->getServices()->has('docker')) {
305 14
            return array(0, '');
306
        }
307
308 3
        $this->streams->out(' +++ docker client install...: ');
309
310
        try {
311 3
            list($status, $message) = $this->getDockerBinaryRepository()->inject($id);
312 1
        } catch (\Exception $e) {
313 1
            $this->streams->out("pipelines internal failure.\n");
314
315 1
            throw new \InvalidArgumentException('inject docker client failed: ' . $e->getMessage(), 1, $e);
316
        }
317
318 2
        $this->streams->out("${message}\n");
319
320 2
        return array($status, $message);
321
    }
322
323
    /**
324
     * @param Image $image
325
     *
326
     * @throws \RuntimeException
327
     * @throws \InvalidArgumentException
328
     */
329
    private function imageLogin(Image $image)
330
    {
331 20
        $login = new ImageLogin($this->exec, $this->env->getResolver());
332 20
        $login->byImage($image);
333 20
    }
334
335
    /**
336
     * @param StepContainer $container
337
     * @param string $dir
338
     * @param bool $copy
339
     * @param Step $step
340
     *
341
     * @return array array(string|null $id, int $status)
342
     */
343
    private function runNewContainer(StepContainer $container, $dir, $copy, Step $step)
344
    {
345 20
        $env = $this->env;
346 20
        $exec = $this->exec;
0 ignored issues
show
Unused Code introduced by
The assignment to $exec is dead and can be removed.
Loading history...
347 20
        $streams = $this->streams;
348
349 20
        $image = $step->getImage();
350
351
        # process docker login if image demands so, but continue on failure
352 20
        $this->imageLogin($image);
353
354 20
        $mountDockerSock = $this->obtainDockerSocketMount();
355
356 20
        $parentName = $env->getValue('PIPELINES_PARENT_CONTAINER_NAME');
357 20
        $hostDeviceDir = $this->pipHostConfigBind($dir);
358 20
        $checkMount = $mountDockerSock && null !== $parentName;
359 20
        $deviceDir = $hostDeviceDir ?: $dir;
360 20
        if ($checkMount && '/app' === $dir && null === $hostDeviceDir) { // FIXME(tk): hard encoded /app
361 2
            $deviceDir = $env->getPipelinesProjectPath($deviceDir);
362 2
            if ($deviceDir === $dir || null === $deviceDir) {
363 2
                $streams->err("pipelines: fatal: can not detect ${dir} mount point. preventing new container.\n");
364
365 2
                return array(null, 1);
366
            }
367
        }
368
369 18
        $mountWorkingDirectory = $copy
370 7
            ? array()
371
            // FIXME(tk): Never mount anything not matching /home/[a-zA-Z][a-zA-Z0-9]*/[^.].*/...
372
            //   + do realpath checking
373
            //   + prevent dot path injections (logical fix first)
374 18
            : array('--volume', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
375
376 18
        list($status, $out, $err) = $container->run(
377
            array(
378 18
                '-i', '--name', $container->getName(),
379 18
                $env->getArgs('-e'),
380 18
                $mountWorkingDirectory, '-e', 'BITBUCKET_CLONE_DIR=/app',
381 18
                $mountDockerSock,
382 18
                '--workdir', '/app', '--detach', '--entrypoint=/bin/sh', $image->getName(),
383
            )
384
        );
385 18
        if (0 !== $status) {
386 1
            $streams->out("    container-id...: *failure*\n\n");
387 1
            $streams->err("pipelines: setting up the container failed\n");
388 1
            $streams->err("${err}\n");
389 1
            $streams->out("${out}\n");
390 1
            $streams->out(sprintf("exit status: %d\n", $status));
391
392 1
            return array(null, $status);
393
        }
394 17
        $id = $container->getDisplayId();
395
396 17
        return array($id, $status);
397
    }
398
399
    /**
400
     * enable docker client inside docker by mounting docker socket
401
     *
402
     * @return array docker socket volume args for docker run, empty if not mounting
403
     */
404
    private function obtainDockerSocketMount()
405
    {
406 20
        $args = array();
407
408
        // FIXME give more controlling options, this is serious /!\
409 20
        if (!$this->flags->useDockerSocket()) {
410 1
            return $args;
411
        }
412
413 19
        $defaultSocketPath = $this->runOpts->getOption('docker.socket.path');
414 19
        $hostPathDockerSocket = $defaultSocketPath;
415
416
        // pipelines inside pipelines
417 19
        $hostPath = $this->pipHostConfigBind($defaultSocketPath);
418 19
        if (null !== $hostPath) {
419
            return array(
420 1
                '-v', sprintf('%s:%s', $hostPath, $defaultSocketPath),
421
            );
422
        }
423
424 18
        $dockerHost = $this->env->getInheritValue('DOCKER_HOST');
425 18
        if (null !== $dockerHost && 0 === strpos($dockerHost, 'unix://')) {
426 1
            $hostPathDockerSocket = LibFs::normalizePath(substr($dockerHost, 7));
427
        }
428
429 18
        $pathDockerSock = $defaultSocketPath;
430
431 18
        if (file_exists($hostPathDockerSocket)) {
432
            $args = array(
433 14
                '-v', sprintf('%s:%s', $hostPathDockerSocket, $pathDockerSock),
434
            );
435
        }
436
437 18
        return $args;
438
    }
439
440
    /**
441
     * get host path from mount point if in pip level 2+
442
     *
443
     * @param mixed $mountPoint
444
     * @return null|string
445
     */
446
    private function pipHostConfigBind($mountPoint)
447
    {
448
        // if there is a parent name, this is level 2+
449 20
        if (null === $this->env->getValue('PIPELINES_PARENT_CONTAINER_NAME')) {
450 16
            return null;
451
        }
452
453 4
        if (null === $pipName = $this->env->getValue('PIPELINES_PIP_CONTAINER_NAME')) {
454 2
            return null;
455
        }
456
457 2
        return Docker::create($this->exec)->hostConfigBind($pipName, $mountPoint);
458
    }
459
460
    /**
461
     * @param Step $step
462
     * @param Streams $streams
463
     * @param Exec $exec
464
     * @param string $name container name
465
     *
466
     * @return null|int should never be null, status, non-zero if a command failed
467
     */
468
    private function runStepScript(Step $step, Streams $streams, Exec $exec, $name)
469
    {
470 15
        $script = $step->getScript();
471
472 15
        $buffer = Lib::cmd("<<'SCRIPT' docker", array(
473 15
            'exec', '-i', $name, '/bin/sh',
474
        ));
475 15
        $buffer .= "\n# this /bin/sh script is generated from a pipelines pipeline:\n";
476 15
        $buffer .= "set -e\n";
477 15
        foreach ($script as $line => $command) {
478 15
            $line && $buffer .= 'printf \'\\n\'' . "\n";
479 15
            $buffer .= 'printf \'\\035+ %s\\n\' ' . Lib::quoteArg($command) . "\n";
480 15
            $buffer .= $command . "\n";
481
        }
482 15
        $buffer .= "SCRIPT\n";
483
484 15
        $status = $exec->pass($buffer, array());
485
486 15
        if (0 !== $status) {
487 2
            $streams->err(sprintf("script non-zero exit status: %d\n", $status));
488
        }
489
490 15
        return $status;
491
    }
492
493
    /**
494
     * @param StepContainer $container
495
     * @param int $status
496
     */
497
    private function shutdownStepContainer(StepContainer $container, $status)
498
    {
499 15
        $flags = $this->flags;
500 15
        $id = $container->getDisplayId();
501
502
        # keep container on error
503 15
        if (0 !== $status && $flags->keepOnError()) {
504 2
            $this->streams->err(sprintf(
505 2
                "error, keeping container id %s\n",
506 2
                substr($id, 0, 12)
507
            ));
508
509 2
            return;
510
        }
511
512
        # keep or kill/remove container
513 13
        $container->killAndRemove($flags->killContainer(), $flags->removeContainer());
514
515 13
        if ($flags->keep()) {
516 1
            $this->streams->out(sprintf(
517 1
                "keeping container id %s\n",
518 1
                substr($id, 0, 12)
519
            ));
520
        }
521 13
    }
522
}
523