Completed
Push — test ( d8d9f2...ee908a )
by Tom
14:20 queued 28s
created

StepRunner::obtainServicesNetwork()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 2
rs 9.9332
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 27
    public function __construct(Runner $runner)
42
    {
43 27
        $this->runner = $runner;
44 27
    }
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 25
    public function runStep(Step $step)
52
    {
53 25
        $dir = $this->runner->getDirectories()->getProjectDirectory();
54 25
        $env = $this->runner->getEnv();
55 25
        $exec = $this->runner->getExec();
0 ignored issues
show
Unused Code introduced by
The assignment to $exec is dead and can be removed.
Loading history...
56 25
        $streams = $this->runner->getStreams();
57
58 25
        $containers = new Containers($this->runner);
59
60 25
        $env->setPipelinesProjectPath($dir);
61
62 25
        $container = $containers->createStepContainer($step);
63
64 25
        $env->setContainerName($container->getName());
65
66 25
        $image = $step->getImage();
67
68
        # launch container
69 25
        $streams->out(sprintf(
70 25
            "\x1D+++ step #%d\n\n    name...........: %s\n    effective-image: %s\n    container......: %s\n",
71 25
            $step->getIndex() + 1,
72 25
            $step->getName() ? '"' . $step->getName() . '"' : '(unnamed)',
73 25
            $image->getName(),
74 25
            $container->getName()
75
        ));
76
77 25
        $id = $container->keepOrKill();
78
79 25
        $deployCopy = $this->runner->getFlags()->deployCopy();
80
81 25
        if (null === $id) {
82 23
            list($id, $status, $out, $err) = $this->runNewContainer($container, $dir, $deployCopy, $step);
83 22
            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 21
        $streams->out(sprintf("    container-id...: %s\n\n", substr($id, 0, 12)));
95
96
        # TODO: different deployments, mount (default), mount-ro, copy
97 21
        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 19
        $deployCopy && $streams('');
104
105 19
        $status = StepScriptRunner::createRunStepScript($this->runner, $container->getName(), $step);
106
107 19
        $this->captureStepArtifacts($step, $deployCopy && 0 === $status, $id, $dir);
108
109 19
        $container->shutdown($status);
110
111 19
        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 19
        if (!$copy) {
141 14
            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 21
        if (!$copy) {
224 14
            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 23
        $env = $this->runner->getEnv();
266
267 23
        $mountDockerSock = $this->obtainDockerSocketMount();
268
269 23
        $mountDockerClient = $this->obtainDockerClientMount($step);
270
271 22
        $mountWorkingDirectory = $this->obtainWorkingDirMount($copy, $dir, $mountDockerSock);
272 22
        if ($mountWorkingDirectory && is_int($mountWorkingDirectory[1])) {
273 2
            return $mountWorkingDirectory + array(2 => '', 3 => '');
274
        }
275
276 20
        $network = $container->getServiceContainers()->obtainNetwork();
277
278
        # process docker login if image demands so, but continue on failure
279 20
        $image = $step->getImage();
280 20
        ImageLogin::loginImage($this->runner->getExec(), $this->runner->getEnv()->getResolver(), null, $image);
281
282 20
        list($status, $out, $err) = $container->run(
283
            array(
284 20
                $network,
285 20
                '-i', '--name', $container->getName(),
286 20
                $env->getArgs('-e'),
287 20
                $env::createArgVarDefinitions('-e', $step->getEnv()),
288 20
                $mountWorkingDirectory, '-e', 'BITBUCKET_CLONE_DIR=/app',
289 20
                $mountDockerSock,
290 20
                $mountDockerClient,
291 20
                $container->obtainUserOptions(),
292 20
                $container->obtainSshOptions(),
293 20
                '--workdir', '/app', '--detach', '--entrypoint=/bin/sh', $image->getName(),
294
            )
295
        );
296 20
        $id = $status ? null : $container->getDisplayId();
297
298 20
        return array($id, $status, $out, $err);
299
    }
300
301
    /**
302
     * @param Step $step
303
     *
304
     * @return string[]
305
     */
306
    private function obtainDockerClientMount(Step $step)
307
    {
308 23
        if (!$step->getServices()->has('docker')) {
309 20
            return array();
310
        }
311
312 3
        $path = $this->runner->getRunOpts()->getOption('docker.client.path');
313
314
        // prefer pip mount over package
315 3
        $hostPath = $this->pipHostConfigBind($path);
316 3
        if (null !== $hostPath) {
317 1
            return array('-v', sprintf('%s:%s:ro', $hostPath, $path));
318
        }
319
320 2
        $local = $this->getDockerBinaryRepository()->getBinaryPath();
321 1
        chmod($local, 0755);
322
323 1
        return array('-v', sprintf('%s:%s:ro', $local, $path));
324
    }
325
326
    /**
327
     * enable docker client inside docker by mounting docker socket
328
     *
329
     * @return array docker socket volume args for docker run, empty if not mounting
330
     */
331
    private function obtainDockerSocketMount()
332
    {
333 23
        $args = array();
334
335
        // FIXME give more controlling options, this is serious /!\
336 23
        if (!$this->runner->getFlags()->useDockerSocket()) {
337 1
            return $args;
338
        }
339
340 22
        $defaultSocketPath = $this->runner->getRunOpts()->getOption('docker.socket.path');
341 22
        $hostPathDockerSocket = $defaultSocketPath;
342
343
        // pipelines inside pipelines
344 22
        $hostPath = $this->pipHostConfigBind($defaultSocketPath);
345 22
        if (null !== $hostPath) {
346
            return array(
347 1
                '-v', sprintf('%s:%s', $hostPath, $defaultSocketPath),
348
            );
349
        }
350
351 21
        $dockerHost = $this->runner->getEnv()->getInheritValue('DOCKER_HOST');
352 21
        if (null !== $dockerHost && 0 === strpos($dockerHost, 'unix://')) {
353 1
            $hostPathDockerSocket = LibFsPath::normalize(substr($dockerHost, 7));
354
        }
355
356 21
        $pathDockerSock = $defaultSocketPath;
357
358 21
        if (file_exists($hostPathDockerSocket)) {
359
            $args = array(
360 18
                '-v', sprintf('%s:%s', $hostPathDockerSocket, $pathDockerSock),
361
            );
362
        }
363
364 21
        return $args;
365
    }
366
367
    /**
368
     * @param bool $copy
369
     * @param string $dir
370
     * @param array $mountDockerSock
371
     *
372
     * @return array mount options or array(null, int $status) for error handling
373
     */
374
    private function obtainWorkingDirMount($copy, $dir, array $mountDockerSock)
375
    {
376 22
        if ($copy) {
377 7
            return array();
378
        }
379
380 15
        $parentName = $this->runner->getEnv()->getValue('PIPELINES_PARENT_CONTAINER_NAME');
381 15
        $hostDeviceDir = $this->pipHostConfigBind($dir);
382 15
        $checkMount = $mountDockerSock && null !== $parentName;
383 15
        $deviceDir = $hostDeviceDir ?: $dir;
384 15
        if ($checkMount && '/app' === $dir && null === $hostDeviceDir) { // FIXME(tk): hard encoded /app
385 2
            $deviceDir = $this->runner->getEnv()->getValue('PIPELINES_PROJECT_PATH');
386 2
            if ($deviceDir === $dir || null === $deviceDir) {
387 2
                $this->runner->getStreams()->err("pipelines: fatal: can not detect ${dir} mount point\n");
388
389 2
                return array(null, 1);
390
            }
391
        }
392
393
        // FIXME(tk): Never mount anything not matching /home/[a-zA-Z][a-zA-Z0-9]*/[^.].*/...
394
        //   + do realpath checking
395
        //   + prevent dot path injections (logical fix first)
396 13
        return array('-v', "${deviceDir}:/app"); // FIXME(tk): hard encoded /app
397
    }
398
399
    /**
400
     * get host path from mount point if in pip level 2+
401
     *
402
     * @param mixed $mountPoint
403
     *
404
     * @return null|string
405
     */
406
    private function pipHostConfigBind($mountPoint)
407
    {
408
        // if there is a parent name, this is level 2+
409 23
        if (null === $pipName = $this->runner->getEnv()->getValue('PIPELINES_PIP_CONTAINER_NAME')) {
410 20
            return null;
411
        }
412
413 3
        return Docker::create($this->runner->getExec())->hostConfigBind($pipName, $mountPoint);
414
    }
415
}
416