Passed
Push — master ( d5c1f5...3b22a1 )
by Tom
05:09 queued 02:51
created

Runner::deployCopy()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 44
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 4

Importance

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