Passed
Push — test ( d48a8e...8face6 )
by Tom
02:59
created

StepRunner   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 450
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 188
c 5
b 0
f 0
dl 0
loc 450
ccs 185
cts 185
cp 1
rs 8.96
wmc 43

11 Methods

Rating   Name   Duplication   Size   Complexity  
A captureArtifactPattern() 0 28 4
A __construct() 0 15 1
A imageLogin() 0 4 1
A shutdownStepContainer() 0 25 4
A captureStepArtifacts() 0 26 4
A deployDockerClient() 0 19 3
A runStepScript() 0 23 4
A deployCopy() 0 38 4
B runNewContainer() 0 66 10
B runStep() 0 57 7
A getDockerBinaryRepository() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like StepRunner often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use StepRunner, and based on these observations, apply Extract Interface, too.

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 18
    public function __construct(
73
        RunOpts $runOpts,
74
        Directories $directories,
75
        Exec $exec,
76
        Flags $flags,
77
        Env $env,
78
        Streams $streams
79
    )
80
    {
81 18
        $this->runOpts = $runOpts;
82 18
        $this->directories = $directories;
83 18
        $this->exec = $exec;
84 18
        $this->flags = $flags;
85 18
        $this->env = $env;
86 18
        $this->streams = $streams;
87 18
    }
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 17
    public function runStep(Step $step)
95
    {
96 17
        $dir = $this->directories->getProjectDirectory();
97 17
        $env = $this->env;
98 17
        $exec = $this->exec;
99 17
        $streams = $this->streams;
100
101 17
        $env->setPipelinesProjectPath($dir);
102
103 17
        $container = StepContainer::create($step, $exec);
104
105 17
        $name = $container->generateName($this->runOpts->getPrefix(), $this->directories->getName());
106 17
        $env->setContainerName($name);
107
108 17
        $image = $step->getImage();
109
110
        # launch container
111 17
        $streams->out(sprintf(
112 17
            "\x1D+++ step #%d\n\n    name...........: %s\n    effective-image: %s\n    container......: %s\n",
113 17
            $step->getIndex() + 1,
114 17
            $step->getName() ? '"' . $step->getName() . '"' : '(unnamed)',
115 17
            $image->getName(),
116 17
            $name
117
        ));
118
119 17
        $id = $container->keepOrKill($this->flags->reuseContainer());
120
121 17
        $deployCopy = $this->flags->deployCopy();
122
123 17
        if (null === $id) {
124 15
            list($id, $status) = $this->runNewContainer($container, $dir, $deployCopy, $step);
125 15
            if (null === $id) {
126 2
                return $status;
127
            }
128
        }
129
130 15
        $streams->out(sprintf("    container-id...: %s\n\n", substr($id, 0, 12)));
131
132
        # TODO: different deployments, mount (default), mount-ro, copy
133 15
        if (null !== $result = $this->deployCopy($deployCopy, $id, $dir)) {
134 2
            return $result;
135
        }
136
137 13
        list($status, $message) = $this->deployDockerClient($step, $id);
138 12
        if (0 !== $status) {
139 1
            $this->streams->err(rtrim($message, "\n") . "\n");
140
141 1
            return $status;
142
        }
143
144 11
        $status = $this->runStepScript($step, $streams, $exec, $name);
145
146 11
        $this->captureStepArtifacts($step, $deployCopy && 0 === $status, $id, $dir);
147
148 11
        $this->shutdownStepContainer($container, $status);
149
150 11
        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 11
    private function captureStepArtifacts(Step $step, $copy, $id, $dir)
175
    {
176
        # capturing artifacts is only supported for deploy copy
177 11
        if (!$copy) {
178 6
            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 15
    private function deployCopy($copy, $id, $dir)
253
    {
254 15
        if (!$copy) {
255 8
            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 13
        if (!$step->getServices()->has('docker')) {
305 10
            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 15
        $login = new ImageLogin($this->exec, $this->env->getResolver());
332 15
        $login->byImage($image);
333 15
    }
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 15
        $env = $this->env;
346 15
        $exec = $this->exec;
347 15
        $streams = $this->streams;
348
349 15
        $image = $step->getImage();
350
351
        # process docker login if image demands so, but continue on failure
352 15
        $this->imageLogin($image);
353
354
        // enable docker client inside docker by mounting docker socket
355
        // FIXME give controlling options, this is serious /!\
356 15
        $mountDockerSock = array();
357 15
        $pathDockerSock = $this->runOpts->getOption('docker.socket.path');
358 15
        if ($this->flags->useDockerSocket() && file_exists($pathDockerSock)) {
359
            $mountDockerSock = array(
360 12
                '-v', sprintf('%s:%s', $pathDockerSock, $pathDockerSock),
361
            );
362
        }
363
364 15
        $parentName = $env->getValue('PIPELINES_PARENT_CONTAINER_NAME');
365 15
        $checkMount = $mountDockerSock && null !== $parentName;
366 15
        $deviceDir = $dir;
367 15
        if ($checkMount && '/app' === $dir) { // FIXME(tk): hard encoded /app
368 1
            $docker = new Docker($exec);
369 1
            $deviceDir = $docker->hostDevice($parentName, $dir);
370 1
            unset($docker);
371 1
            if ($deviceDir === $dir) {
372 1
                $deviceDir = $env->getPipelinesProjectPath($deviceDir);
373
            }
374 1
            if ($deviceDir === $dir) {
375 1
                $streams->err("pipelines: fatal: can not detect ${dir} mount point. preventing new container.\n");
376
377 1
                return array(null, 1);
378
            }
379
        }
380
381 14
        $mountWorkingDirectory = $copy
382 7
            ? array()
383
            // FIXME(tk): Never mount anything not matching /home/[a-zA-Z][a-zA-Z0-9]*/[^.].*/...
384
            //   + do realpath checking
385
            //   + prevent dot path injections (logical fix first)
386 14
            : array('--volume', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
387
388 14
        list($status, $out, $err) = $container->run(
389
            array(
390 14
                '-i', '--name', $container->getName(),
391 14
                $env->getArgs('-e'),
392 14
                $mountWorkingDirectory, '-e', 'BITBUCKET_CLONE_DIR=/app',
393 14
                $mountDockerSock,
394 14
                '--workdir', '/app', '--detach', '--entrypoint=/bin/sh', $image->getName(),
395
            )
396
        );
397 14
        if (0 !== $status) {
398 1
            $streams->out("    container-id...: *failure*\n\n");
399 1
            $streams->err("pipelines: setting up the container failed\n");
400 1
            $streams->err("${err}\n");
401 1
            $streams->out("${out}\n");
402 1
            $streams->out(sprintf("exit status: %d\n", $status));
403
404 1
            return array(null, $status);
405
        }
406 13
        $id = $container->getDisplayId();
407
408 13
        return array($id, $status);
409
    }
410
411
    /**
412
     * @param Step $step
413
     * @param Streams $streams
414
     * @param Exec $exec
415
     * @param string $name container name
416
     *
417
     * @return null|int should never be null, status, non-zero if a command failed
418
     */
419
    private function runStepScript(Step $step, Streams $streams, Exec $exec, $name)
420
    {
421 11
        $script = $step->getScript();
422
423 11
        $buffer = Lib::cmd("<<'SCRIPT' docker", array(
424 11
            'exec', '-i', $name, '/bin/sh',
425
        ));
426 11
        $buffer .= "\n# this /bin/sh script is generated from a pipelines pipeline:\n";
427 11
        $buffer .= "set -e\n";
428 11
        foreach ($script as $line => $command) {
429 11
            $line && $buffer .= 'printf \'\\n\'' . "\n";
430 11
            $buffer .= 'printf \'\\035+ %s\\n\' ' . Lib::quoteArg($command) . "\n";
431 11
            $buffer .= $command . "\n";
432
        }
433 11
        $buffer .= "SCRIPT\n";
434
435 11
        $status = $exec->pass($buffer, array());
436
437 11
        if (0 !== $status) {
438 2
            $streams->err(sprintf("script non-zero exit status: %d\n", $status));
439
        }
440
441 11
        return $status;
442
    }
443
444
    /**
445
     * @param StepContainer $container
446
     * @param int $status
447
     */
448
    private function shutdownStepContainer(StepContainer $container, $status)
449
    {
450 11
        $flags = $this->flags;
451 11
        $id = $container->getDisplayId();
452
453
        # keep container on error
454 11
        if (0 !== $status && $flags->keepOnError()) {
455 2
            $this->streams->err(sprintf(
456 2
                "error, keeping container id %s\n",
457 2
                substr($id, 0, 12)
458
            ));
459
460 2
            return;
461
        }
462
463
        # keep or kill/remove container
464 9
        $container->killAndRemove(
465 9
            $flags->killContainer(),
466 9
            $flags->removeContainer()
467
        );
468
469 9
        if ($flags->keep()) {
470 1
            $this->streams->out(sprintf(
471 1
                "keeping container id %s\n",
472 1
                substr($id, 0, 12)
473
            ));
474
        }
475 9
    }
476
}
477