Passed
Push — test ( 964254...4cd390 )
by Tom
02:59
created

StepRunner::getProject()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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