Passed
Push — master ( 3b22a1...94154d )
by Tom
03:44
created

Runner::runStep()   C

Complexity

Conditions 10
Paths 48

Size

Total Lines 76
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 10.0018

Importance

Changes 0
Metric Value
cc 10
eloc 49
nc 48
nop 2
dl 0
loc 76
ccs 36
cts 37
cp 0.973
crap 10.0018
rs 5.7198
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines;
6
7
use Ktomk\Pipelines\Cli\Docker;
8
use Ktomk\Pipelines\Cli\Exec;
9
use Ktomk\Pipelines\Cli\Streams;
10
use Ktomk\Pipelines\File\Image;
11
use Ktomk\Pipelines\Runner\ArtifactSource;
12
use Ktomk\Pipelines\Runner\DockerLogin;
13
use Ktomk\Pipelines\Runner\Env;
14
15
/**
16
 * Pipeline runner with docker under the hood
17
 */
18
class Runner
19
{
20
    const FLAGS = 11;
21
    const FLAG_DOCKER_REMOVE = 1;
22
    const FLAG_DOCKER_KILL = 2;
23
    const FLAG_DEPLOY_COPY = 4; # copy working dir into container
24
    const FLAG_KEEP_ON_ERROR = 8;
25
26
    const STATUS_NO_STEPS = 1;
27
    const STATUS_RECURSION_DETECTED = 127;
28
29
    /**
30
     * @var string
31
     */
32
    private $prefix;
33
34
    /**
35
     * @var string
36
     */
37
    private $directory;
38
39
    /**
40
     * @var Exec
41
     */
42
    private $exec;
43
44
    /**
45
     * @var int
46
     */
47
    private $flags;
48
49
    /**
50
     * @var Env
51
     */
52
    private $env;
53
    /**
54
     * @var Streams
55
     */
56
    private $streams;
57
58
    /**
59
     * DockerSession constructor.
60
     *
61
     * @param string $prefix
62
     * @param string $directory source repository root
63
     * @param Exec $exec
64
     * @param int $flags [optional]
65
     * @param Env $env [optional]
66
     * @param Streams $streams [optional]
67
     */
68 12
    public function __construct(
69
        $prefix,
70
        $directory,
71
        Exec $exec,
72
        $flags = null,
73
        Env $env = null,
74
        Streams $streams = null
75
    )
76
    {
77 12
        $this->prefix = $prefix;
78
79 12
        $this->directory = $directory;
80 12
        $this->exec = $exec;
81 12
        $this->flags = null === $flags ? self::FLAGS : $flags;
82 12
        $this->env = null === $env ? Env::create() : $env;
83 12
        $this->streams = null === $streams ? Streams::create() : $streams;
84 12
    }
85
86
    /**
87
     * @param Pipeline $pipeline
88
     * @throws \RuntimeException
89
     * @return int
90
     */
91 12
    public function run(Pipeline $pipeline)
92
    {
93 12
        $hasId = $this->env->setPipelinesId($pipeline->getId()); # TODO give Env an addPipeline() method (compare addReference)
94 12
        if ($hasId) {
95 1
            $this->streams->err(sprintf(
96 1
                "pipelines: won't start pipeline '%s'; pipeline inside pipelines recursion detected\n",
97 1
                $pipeline->getId()
98
            ));
99
100 1
            return self::STATUS_RECURSION_DETECTED;
101
        }
102
103 11
        $steps = $pipeline->getSteps();
104 11
        foreach ($steps as $index => $step) {
105 10
            $status = $this->runStep($step, $index);
106 10
            if (0 !== $status) {
107 10
                return $status;
108
            }
109
        }
110
111 7
        if (!isset($status)) {
112 1
            $this->streams->err("pipelines: pipeline with no step to execute\n");
113
114 1
            return self::STATUS_NO_STEPS;
115
        }
116
117 6
        return $status;
118
    }
119
120
    /**
121
     * @param Step $step
122
     * @param int $index
123
     * @throws \RuntimeException
124
     * @return int exit status
125
     */
126 10
    public function runStep(Step $step, $index)
127
    {
128 10
        $prefix = $this->prefix;
129 10
        $dir = $this->directory;
130 10
        $env = $this->env;
131 10
        $exec = $this->exec;
132 10
        $streams = $this->streams;
133
134 10
        $docker = new Docker($exec);
135
136 10
        $name = $prefix . '-' . Lib::generateUuid();
137 10
        $image = $step->getImage();
138 10
        $env->setContainerName($name);
139
140
        # launch container
141 10
        $streams->out(sprintf(
142 10
            "\x1D+++ step #%d\n\n    name...........: %s\n    effective-image: %s\n    container......: %s\n",
143 10
            $index,
144 10
            $step->getName() ? '"' . $step->getName() . '"' : '(unnamed)',
145 10
            $image->getName(),
146 10
            $name
147
        ));
148
149
        # process docker login if image demands so, but continue on failure
150 10
        $this->imageLogin($image);
151
152 10
        $copy = (bool)($this->flags & self::FLAG_DEPLOY_COPY);
153
154
        // docker client inside docker
155
        // FIXME give controlling options, this is serious /!\
156 10
        $mountDockerSock = array();
157 10
        if (file_exists('/var/run/docker.sock')) {
158
            $mountDockerSock = array(
159
                '-v', '/var/run/docker.sock:/var/run/docker.sock',
160
            );
161
        }
162
163 10
        $parentName = $env->getValue('PIPELINES_PARENT_CONTAINER_NAME');
164 10
        $checkMount = $mountDockerSock && null !== $parentName;
165 10
        $deviceDir = $checkMount ? $docker->hostDevice($parentName, $dir) : $dir;
166
167 10
        $mountWorkingDirectory = $copy
168 6
            ? array()
169 10
            : array('--volume', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
170
171
        $status = $exec->capture('docker', array(
172
            'run', '-i', '--name', $name,
173
            $env->getArgs('-e'),
174
            $mountWorkingDirectory, '-e', 'BITBUCKET_CLONE_DIR=/app',
175
            $mountDockerSock,
176
            '--workdir', '/app', '--detach', $image->getName()
177
        ), $out, $err);
178
        if (0 !== $status) {
179
            $streams->out("    container-id...: *failure*\n\n");
180
            $streams->err("pipelines: setting up the container failed\n");
181
            $streams->err("${err}\n");
182
            $streams->out("${out}\n");
183 1
            $streams->out(sprintf("exit status: %d\n", $status));
184
185 1
            return $status;
186
        }
187 9
        $id = rtrim($out) ?: "*dry-run*"; # side-effect: internal exploit of no output with true exit status
188 9
        $streams->out(sprintf("    container-id...: %s\n\n", substr($id, 0, 12)));
189
190
        # TODO: different deployments, mount (default), mount-ro, copy
191 9
        if (null !== $result = $this->deployCopy($copy, $id, $dir)) {
192 2
            return $result;
193
        }
194
195 7
        $status = $this->runStepScript($step, $streams, $exec, $name);
196
197 7
        $this->captureStepArtifacts($step, $copy && 0 === $status, $id, $dir);
198
199 7
        $this->shutdownStepContainer($status, $id, $exec, $name);
200
201 7
        return $status;
202
    }
203
204
    /**
205
     * @param Image $image
206
     */
207
    private function imageLogin(Image $image)
208
    {
209 10
        $login = new DockerLogin($this->exec, $this->env->getResolver());
210 10
        $login->byImage($image);
211 10
    }
212
213
    /**
214
     * @param bool $copy
215
     * @param string $id container id
216
     * @param string $dir directory to copy contents into container
217
     * @return null|int null if all clear, integer for exit status
218
     */
219
    private function deployCopy($copy, $id, $dir)
220
    {
221 9
        if (!$copy) {
222 3
            return null;
223
        }
224
225 6
        $streams = $this->streams;
226 6
        $exec = $this->exec;
227
228 6
        $streams->out("\x1D+++ copying files into container...\n");
229
230 6
        $tmpDir = sys_get_temp_dir() . '/pipelines/cp';
231 6
        Lib::fsMkdir($tmpDir);
232 6
        Lib::fsSymlink($dir, $tmpDir . '/app');
233 6
        $cd = Lib::cmd('cd', array($tmpDir . '/.'));
234 6
        $tar = Lib::cmd(
235 6
            'tar',
236
            array(
237 6
                'c', '-h', '-f', '-', '--no-recursion', 'app')
238
        );
239 6
        $dockerCp = Lib::cmd(
240 6
            'docker ',
241
            array(
242 6
                'cp', '-', $id . ':/.')
243
        );
244 6
        $status = $exec->pass("${cd} && echo 'app' | ${tar} | ${dockerCp}", array());
245 6
        Lib::fsUnlink($tmpDir . '/app');
246 6
        if (0 !== $status) {
247 1
            $streams->err('pipelines: deploy copy failure\n');
248
249 1
            return $status;
250
        }
251
252 5
        $cd = Lib::cmd('cd', array($dir . '/.'));
253 5
        $tar = Lib::cmd(
254 5
            'tar',
255
            array(
256 5
                'c', '-f', '-', '.')
257
        );
258 5
        $dockerCp = Lib::cmd(
259 5
            'docker ',
260
            array(
261 5
                'cp', '-', $id . ':/app')
262
        );
263 5
        $status = $exec->pass("${cd} && ${tar} | ${dockerCp}", array());
264 5
        if (0 !== $status) {
265 1
            $streams->err('pipelines: deploy copy failure\n');
266
267 1
            return $status;
268
        }
269
270 4
        $streams("");
271
272 4
        return null;
273
    }
274
275
    /**
276
     * @param Step $step
277
     * @param Streams $streams
278
     * @param Exec $exec
279
     * @param string $name container name
280
     * @return null|int should never be null, status, non-zero if a command failed
281
     */
282
    private function runStepScript(Step $step, Streams $streams, Exec $exec, $name)
283
    {
284 7
        $script = $step->getScript();
285 7
        $status = null;
286
287 7
        foreach ($script as $line => $command) {
288 7
            $streams->out(sprintf("\x1D+ %s\n", $command));
289 7
            $status = $exec->pass('docker', array(
290 7
                'exec', '-i', $name, '/bin/sh', '-c', $command,
291
            ));
292 7
            $streams->out(sprintf("\n"));
293 7
            if (0 !== $status) {
294 7
                break;
295
            }
296
        }
297
298 7
        return $status;
299
    }
300
301
    /**
302
     * @param Step $step
303
     * @param bool $copy
304
     * @param string $id container id
305
     * @param string $dir to put artifacts in (project directory)
306
     */
307
    private function captureStepArtifacts(Step $step, $copy, $id, $dir)
308
    {
309
        # capturing artifacts is only supported for deploy copy
310 7
        if (!$copy) {
311 3
            return;
312
        }
313
314 4
        $artifacts = $step->getArtifacts();
315
316 4
        if (null === $artifacts) {
317 1
            return;
318
        }
319
320 3
        $exec = $this->exec;
321 3
        $streams = $this->streams;
322
323 3
        $streams->out("\x1D+++ copying artifacts from container...\n");
324
325 3
        $source = new ArtifactSource($exec, $id, $dir);
326
327 3
        $patterns = $artifacts->getPatterns();
328 3
        foreach ($patterns as $pattern) {
329 3
            $this->captureArtifactPattern($source, $pattern, $dir);
330
        }
331
332 3
        $streams("");
333 3
    }
334
335
    /**
336
     * @see Runner::captureStepArtifacts()
337
     *
338
     * @param ArtifactSource $source
339
     * @param string $pattern
340
     * @param string $dir
341
     * @throws \RuntimeException
342
     */
343
    private function captureArtifactPattern(ArtifactSource $source, $pattern, $dir)
344
    {
345 3
        $exec = $this->exec;
346 3
        $streams = $this->streams;
347
348 3
        $id = $source->getId();
349 3
        $paths = $source->findByPattern($pattern);
350 3
        if (empty($paths)) {
351 1
            return;
352
        }
353
354 2
        $chunkSize = 2048;
355 2
        $chunks = array_chunk($paths, $chunkSize, true);
356
357 2
        foreach ($chunks as $paths) {
358 2
            $docker = Lib::cmd('docker', array('exec', '-w', '/app', $id));
359 2
            $tar = Lib::cmd('tar', array('c', '-f', '-', $paths));
360 2
            $unTar = Lib::cmd('tar', array('x', '-f', '-', '-C', $dir));
361
362 2
            $status = $exec->pass($docker . ' ' . $tar . ' | ' . $unTar, array());
363
364 2
            if (0 !== $status) {
365 1
                $streams->err(
366 2
                    sprintf("pipelines: Artifact failure: '%s' (%d, %d paths)\n", $pattern, $status, count($paths))
367
                );
368
            }
369
        }
370 2
    }
371
372
    /**
373
     * @param int $status
374
     * @param string $id container id
375
     * @param Exec $exec
376
     * @param string $name container name
377
     * @throws \RuntimeException
378
     */
379
    private function shutdownStepContainer($status, $id, Exec $exec, $name)
380
    {
381 7
        $flags = $this->flags;
382
383
        # keep container on error
384 7
        if (0 !== $status && $flags & self::FLAG_KEEP_ON_ERROR) {
385 1
            $this->streams->err(sprintf(
386 1
                "exit status %d, keeping container id %s\n",
387 1
                $status,
388 1
                substr($id, 0, 12)
389
            ));
390
391 1
            return;
392
        }
393
394
        # keep or remove container
395 6
        if ($flags & self::FLAG_DOCKER_KILL) {
396 2
            $exec->capture('docker', array('kill', $name));
397
        }
398
399 6
        if ($flags & self::FLAG_DOCKER_REMOVE) {
400 2
            $exec->capture('docker', array('rm', $name));
401
        }
402 6
    }
403
}
404