Passed
Push — master ( 5150f4...648c95 )
by Gaetano
07:39
created

MigrateCommand::setOutput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Command;
4
5
use Symfony\Component\Console\Input\ArrayInput;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Symfony\Component\Console\Helper\Table;
10
use Symfony\Component\Console\Question\ConfirmationQuestion;
11
use Symfony\Component\Process\ProcessBuilder;
12
use Symfony\Component\Process\PhpExecutableFinder;
13
use Kaliop\eZMigrationBundle\API\Value\MigrationDefinition;
14
use Kaliop\eZMigrationBundle\API\Value\Migration;
15
use Kaliop\eZMigrationBundle\API\Exception\AfterMigrationExecutionException;
16
use Kaliop\eZMigrationBundle\Core\MigrationService;
17
18
/**
19
 * Command to execute the available migration definitions.
20
 */
21
class MigrateCommand extends AbstractCommand
22
{
23
    // in between QUIET and NORMAL
24
    const VERBOSITY_CHILD = 0.5;
25
    /** @var OutputInterface $output */
26
    protected $output;
27
    /** @var OutputInterface $output */
28
    protected $errOutput;
29
    protected $verbosity = OutputInterface::VERBOSITY_NORMAL;
30
31
    protected $subProcessTimeout = 86400;
32
    protected $subProcessErrorString = '';
33
34
    const COMMAND_NAME = 'kaliop:migration:migrate';
35
36 78
    /**
37
     * Set up the command.
38 78
     *
39
     * Define the name, options and help text.
40
     */
41 78
    protected function configure()
42 78
    {
43 78
        parent::configure();
44
45 78
        $this
46 78
            ->setName(self::COMMAND_NAME)
47 78
            ->setAliases(array('kaliop:migration:update'))
48 78
            ->setDescription('Execute available migration definitions.')
49 78
            // nb: when adding options, remember to forward them to sub-commands executed in 'separate-process' mode
50 78
            ->addOption('admin-login', 'a', InputOption::VALUE_REQUIRED, "Login of admin account used whenever elevated privileges are needed (user id 14 used by default)")
51 78
            ->addOption('clear-cache', 'c', InputOption::VALUE_NONE, "Clear the cache after the command finishes")
52 78
            ->addOption('default-language', 'l', InputOption::VALUE_REQUIRED, "Default language code that will be used if no language is provided in migration steps")
53 78
            ->addOption('force', 'f', InputOption::VALUE_NONE, "Force (re)execution of migrations already DONE, SKIPPED or FAILED. Use with great care!")
54 78
            ->addOption('ignore-failures', 'i', InputOption::VALUE_NONE, "Keep executing migrations even if one fails")
55 78
            ->addOption('no-interaction', 'n', InputOption::VALUE_NONE, "Do not ask any interactive question")
56 78
            ->addOption('no-transactions', 'u', InputOption::VALUE_NONE, "Do not use a repository transaction to wrap each migration. Unsafe, but needed for legacy slot handlers")
57
            ->addOption('path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, "The directory or file to load the migration definitions from")
58
            ->addOption('separate-process', 'p', InputOption::VALUE_NONE, "Use a separate php process to run each migration. Safe if your migration leak memory. A tad slower")
59
            ->addOption('force-sigchild-handling', null, InputOption::VALUE_NONE, "When using a separate php process to run each migration, tell Symfony that php was compiled with --enable-sigchild option")
60
            ->addOption('child', null, InputOption::VALUE_NONE, "*DO NOT USE* Internal option for when forking separate processes")
61
            ->setHelp(<<<EOT
62
The <info>kaliop:migration:migrate</info> command loads and executes migrations:
63
64
    <info>./ezpublish/console kaliop:migration:migrate</info>
65 78
66
You can optionally specify the path to migration definitions with <info>--path</info>:
67
68
    <info>./ezpublish/console kaliop:migrations:migrate --path=/path/to/bundle/version_directory --path=/path/to/bundle/version_directory/single_migration_file</info>
69
EOT
70
            );
71
    }
72
73
    /**
74 47
     * Execute the command.
75
     *
76 47
     * @param InputInterface $input
77
     * @param OutputInterface $output
78 47
     * @return null|int null or 0 if everything went fine, or an error code
79 47
     */
80
    protected function execute(InputInterface $input, OutputInterface $output)
81 47
    {
82
        $start = microtime(true);
83
84
        $this->setOutput($output);
85 47
        $this->setVerbosity($output->getVerbosity());
86
87 47
        if ($input->getOption('child')) {
88
            $this->setVerbosity(self::VERBOSITY_CHILD);
89 47
        }
90
91 47
        $this->getContainer()->get('ez_migration_bundle.step_executed_listener.tracing')->setOutput($output);
92
93 47
        $migrationService = $this->getMigrationService();
94
95
        $force = $input->getOption('force');
96
97
        $toExecute = $this->buildMigrationsList($input->getOption('path'), $migrationService, $force);
0 ignored issues
show
Bug introduced by
It seems like $input->getOption('path') can also be of type boolean and string; however, parameter $paths of Kaliop\eZMigrationBundle...::buildMigrationsList() does only seem to accept string[], maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

97
        $toExecute = $this->buildMigrationsList(/** @scrutinizer ignore-type */ $input->getOption('path'), $migrationService, $force);
Loading history...
98 47
99
        if (!count($toExecute)) {
100
            $output->writeln('<info>No migrations to execute</info>');
101 47
            return 0;
102
        }
103
104
        $this->printMigrationsList($toExecute, $input, $output);
105 47
106
        // ask user for confirmation to make changes
107
        if (!$this->askForConfirmation($input, $output)) {
108
            return 0;
109
        }
110
111
        if ($input->getOption('separate-process')) {
112
            $builder = new ProcessBuilder();
113
            $executableFinder = new PhpExecutableFinder();
114 47
            if (false !== $php = $executableFinder->find()) {
115 47
                $builder->setPrefix($php);
116 47
            }
117
            $builderArgs = $this->createChildProcessArgs($input);
118
        }
119 47
120
        $forceSigChild = $input->getOption('force-sigchild-handling');
121
122 47
        $executed = 0;
123 9
        $failed = 0;
124 9
        $skipped = 0;
125 9
126
        /** @var MigrationDefinition $migrationDefinition */
127
        foreach ($toExecute as $name => $migrationDefinition) {
128 38
129
            // let's skip migrations that we know are invalid - user was warned and he decided to proceed anyway
130 38
            if ($migrationDefinition->status == MigrationDefinition::STATUS_INVALID) {
131
                $output->writeln("<comment>Skipping $name</comment>\n");
132
                $skipped++;
133
                continue;
134
            }
135
136
            $this->writeln("<info>Processing $name</info>");
137
138
            if ($input->getOption('separate-process')) {
139
140
                try {
141
                    /// @todo in quiet mode, we could suppress output of the sub-command...
142
                    $this->executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs, true, $forceSigChild);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $builderArgs does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $builder does not seem to be defined for all execution paths leading up to this point.
Loading history...
143
144
                    $executed++;
145
                } catch (\Exception $e) {
146
                    if ($input->getOption('ignore-failures')) {
147
                        $this->errOutput->writeln("\n<error>Migration failed! Reason: " . $e->getMessage() . "</error>\n");
148
                        $failed++;
149
                        continue;
150
                    }
151
                    if ($e instanceof AfterMigrationExecutionException) {
152
                        $this->errOutput->writeln("\n<error>Failure after migration end! Reason: " . $e->getMessage() . "</error>");
153 38
                    } else {
154
155 30
                        $errorMessage = $e->getMessage();
156 8
                        if ($errorMessage == $this->subProcessErrorString) {
157 8
                            // we have already echoed the error message while the subprocess was executing
158
                            $errorMessage = "see above";
159
                        } else {
160
                            $errorMessage = preg_replace('/^\n*Migration aborted! Reason: */', '', $e->getMessage());
161
                        }
162 8
163 38
                        $this->errOutput->writeln("\n<error>Migration aborted! Reason: " . $errorMessage . "</error>");
164
                    }
165
                    return 1;
166
                }
167
168
            } else {
169 39
170
                try {
171
                    $this->executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input);
172
173
                    $executed++;
174
                } catch (\Exception $e) {
175 39
                    if ($input->getOption('ignore-failures')) {
176 39
                        $this->errOutput->writeln("\n<error>Migration failed! Reason: " . $e->getMessage() . "</error>\n");
177 39
                        $failed++;
178
                        continue;
179
                    }
180
                    $this->errOutput->writeln("\n<error>Migration aborted! Reason: " . $e->getMessage() . "</error>");
181 39
                    return 1;
182
                }
183 39
184
            }
185 38
        }
186
187 38
        if ($input->getOption('clear-cache')) {
188 38
            $command = $this->getApplication()->find('cache:clear');
189 38
            $inputArray = new ArrayInput(array('command' => 'cache:clear'));
190 38
            $command->run($inputArray, $output);
191 38
        }
192 38
193
        $time = microtime(true) - $start;
194 30
        $this->writeln("Executed $executed migrations, failed $failed, skipped $skipped");
195
        if ($input->getOption('separate-process')) {
196
            // in case of using subprocesses, we can not measure max memory used
197
            $this->writeln("Time taken: ".sprintf('%.2f', $time)." secs");
198
        } else {
199
            $this->writeln("Time taken: ".sprintf('%.2f', $time)." secs, memory: ".sprintf('%.2f', (memory_get_peak_usage(true) / 1000000)). ' MB');
200
        }
201
    }
202
203
    /**
204
     * @param MigrationDefinition $migrationDefinition
205
     * @param bool $force
206
     * @param MigrationService $migrationService
207
     * @param InputInterface $input
208
     */
209
    protected function executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input)
210
    {
211
        $migrationService->executeMigration(
212
            $migrationDefinition,
213
            !$input->getOption('no-transactions'),
214
            $input->getOption('default-language'),
0 ignored issues
show
Bug introduced by
It seems like $input->getOption('default-language') can also be of type string[]; however, parameter $defaultLanguageCode of Kaliop\eZMigrationBundle...ice::executeMigration() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

214
            /** @scrutinizer ignore-type */ $input->getOption('default-language'),
Loading history...
215
            $input->getOption('admin-login'),
216
            $force,
217
            $input->getOption('force-sigchild-handling')
218
        );
219
    }
220
221
    /**
222
     * @param MigrationDefinition $migrationDefinition
223
     * @param MigrationService $migrationService
224
     * @param ProcessBuilder $builder
225
     * @param array $builderArgs
226
     * @param bool $feedback
227
     * @param null|bool $forceSigchild
228
     */
229
    protected function executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs, $feedback = true, $forceSigchild = null)
230
    {
231
        $process = $builder
232
            ->setArguments(array_merge($builderArgs, array('--path=' . $migrationDefinition->path)))
233
            ->getProcess();
234
235
        if ($feedback) {
236
            $this->writeln('<info>Executing: ' . $process->getCommandLine() . '</info>', OutputInterface::VERBOSITY_VERBOSE);
237
        }
238
239
        // allow long migrations processes by default
240
        $process->setTimeout($this->subProcessTimeout);
241
        // allow forcing handling of sigchild. Useful on eg. Debian and Ubuntu
242
        if ($forceSigchild !== null) {
243
            $process->setEnhanceSigchildCompatibility($forceSigchild);
244
        }
245
        // and give immediate feedback to the user...
246
        // NB: if the subprocess writes to stderr then terminates with non-0 exit code, this will lead us to echoing the
247
        // error text twice, once here and once at the end of execution of this command.
248
        // In order to avoid that, since we can not know at this time what the subprocess exit code will be, we should
249
        // somehow still print the error text now, and compare it to what we gt at the end...
250
        $process->run(
251
            $feedback ?
252
                function($type, $buffer) {
253 47
                    if ($type == 'err') {
254
                        $this->subProcessErrorString .= $buffer;
255 47
                        $this->errOutput->write(preg_replace('/^\n*Migration aborted! Reason: */', '', $buffer));
256 47
                    } else {
257
                        $this->output->write($buffer);
258 47
                    }
259 47
                }
260
                :
261
                function($type, $buffer) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

261
                function(/** @scrutinizer ignore-unused */ $type, $buffer) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $buffer is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

261
                function($type, /** @scrutinizer ignore-unused */ $buffer) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
262
                }
263
        );
264 47
265 47
        if (!$process->isSuccessful()) {
266 47
            $errorOutput = $process->getErrorOutput();
267 47
            /// @todo should we always add the exit code to the error message, even when $errorOutput is not null ?
268
            if ($errorOutput === '') {
269
                $errorOutput = "(separate process used to execute migration failed with no stderr output. Its exit code was: " . $process->getExitCode();
270
                if ($process->getExitCode() == -1) {
271
                    $errorOutput .= ". If you are using Debian or Ubuntu linux, please consider using the --force-sigchild-handling option.";
272
                }
273 47
                $errorOutput .= ")";
274
            }
275
            throw new \Exception($errorOutput);
276
        }
277
278
        // There are cases where the separate process dies halfway but does not return a non-zero code.
279
        // That's why we double-check here if the migration is still tagged as 'started'...
280
        /** @var Migration $migration */
281
        $migration = $migrationService->getMigration($migrationDefinition->name);
282
283
        if (!$migration) {
0 ignored issues
show
introduced by
$migration is of type Kaliop\eZMigrationBundle\API\Value\Migration, thus it always evaluated to true.
Loading history...
284
            // q: shall we add the migration to the db as failed? In doubt, we let it become a ghost, disappeared without a trace...
285
            throw new \Exception("After the separate process charged to execute the migration finished, the migration can not be found in the database any more.");
286
        } else if ($migration->status == Migration::STATUS_STARTED) {
287 47
            $errorMsg = "The separate process charged to execute the migration left it in 'started' state. Most likely it died halfway through execution.";
288
            $migrationService->endMigration(New Migration(
289 47
                $migration->name,
290
                $migration->md5,
291
                $migration->path,
292
                $migration->executionDate,
293
                Migration::STATUS_FAILED,
294
                ($migration->executionError != '' ? ($errorMsg . ' ' . $migration->executionError) : $errorMsg)
295
            ));
296
            throw new \Exception($errorMsg);
297
        }
298
    }
299 47
300
    /**
301 47
     * @param string[] $paths
302 47
     * @param MigrationService $migrationService
303 47
     * @param bool $force when true, look not only for TODO migrations, but also DONE, SKIPPED, FAILED ones (we still omit STARTED and SUSPENDED ones)
304 47
     * @return MigrationDefinition[]
305 47
     *
306 9
     * @todo this does not scale well with many definitions or migrations
307
     */
308 47
    protected function buildMigrationsList($paths, $migrationService, $force = false)
309 47
    {
310 47
        $migrationDefinitions = $migrationService->getMigrationsDefinitions($paths);
311 47
        $migrations = $migrationService->getMigrations();
312
313
        $allowedStatuses = array(Migration::STATUS_TODO);
314
        if ($force) {
315 47
            $allowedStatuses = array_merge($allowedStatuses, array(Migration::STATUS_DONE, Migration::STATUS_FAILED, Migration::STATUS_SKIPPED));
316 47
        }
317
318 47
        // filter away all migrations except 'to do' ones
319 47
        $toExecute = array();
320 47
        foreach ($migrationDefinitions as $name => $migrationDefinition) {
321
            if (!isset($migrations[$name]) || (($migration = $migrations[$name]) && in_array($migration->status, $allowedStatuses))) {
322
                $toExecute[$name] = $migrationService->parseMigrationDefinition($migrationDefinition);
323 47
            }
324 47
        }
325
326 47
        // if user wants to execute 'all' migrations: look for some which are registered in the database even if not
327
        // found by the loader
328 47
        if (empty($paths)) {
329
            foreach ($migrations as $migration) {
330
                if (in_array($migration->status, $allowedStatuses) && !isset($toExecute[$migration->name])) {
331
                    $migrationDefinitions = $migrationService->getMigrationsDefinitions(array($migration->path));
332
                    if (count($migrationDefinitions)) {
333
                        $migrationDefinition = reset($migrationDefinitions);
334
                        $toExecute[$migration->name] = $migrationService->parseMigrationDefinition($migrationDefinition);
335
                    } else {
336
                        // q: shall we raise a warning here ?
337
                    }
338
                }
339
            }
340 47
        }
341 47
342
        ksort($toExecute);
343
344
        return $toExecute;
345 47
    }
346
347
    /**
348
     * @param MigrationDefinition[] $toExecute
349
     * @param InputInterface $input
350
     * @param OutputInterface $output
351
     *
352
     * @todo use a more compact output when there are *many* migrations
353 47
     */
354
    protected function printMigrationsList($toExecute, InputInterface $input, OutputInterface $output)
355 47
    {
356 47
        $data = array();
357
        $i = 1;
358 47
        foreach ($toExecute as $name => $migrationDefinition) {
359
            $notes = '';
360 47
            if ($migrationDefinition->status != MigrationDefinition::STATUS_PARSED) {
361
                $notes = '<error>' . $migrationDefinition->parsingError . '</error>';
362 47
            }
363 47
            $data[] = array(
364
                $i++,
365 47
                $name,
366
                $notes
367 47
            );
368 47
        }
369
370
        if (!$input->getOption('child')) {
371
            $table = new Table($output);
372
            $table
373
                ->setHeaders(array('#', 'Migration', 'Notes'))
374
                ->setRows($data);
375
            $table->render();
376
        }
377
378
        $this->writeln('');
379
    }
380
381
    protected function askForConfirmation(InputInterface $input, OutputInterface $output, $nonIteractiveOutput = "=============================================\n")
382
    {
383
        if ($input->isInteractive() && !$input->getOption('no-interaction')) {
384
            $dialog = $this->getHelperSet()->get('question');
385
            if (!$dialog->ask(
0 ignored issues
show
Bug introduced by
The method ask() does not exist on Symfony\Component\Console\Helper\Helper. It seems like you code against a sub-type of Symfony\Component\Console\Helper\Helper such as Symfony\Component\Console\Helper\QuestionHelper or Symfony\Component\Console\Helper\DialogHelper. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

385
            if (!$dialog->/** @scrutinizer ignore-call */ ask(
Loading history...
386
                $input,
387
                $output,
388
                new ConfirmationQuestion('<question>Careful, the database will be modified. Do you want to continue Y/N ?</question>', false)
389
            )
390
            ) {
391
                $output->writeln('<error>Migration execution cancelled!</error>');
392
                return 0;
393
            }
394
        } else {
395
            if ($nonIteractiveOutput != '') {
396
                $this->writeln("$nonIteractiveOutput");
397
            }
398
        }
399
400
        return 1;
401
    }
402
403
    /**
404
     * Returns the command-line arguments needed to execute a migration in a separate subprocess (omitting 'path')
405
     * @param InputInterface $input
406
     * @return array
407
     */
408
    protected function createChildProcessArgs(InputInterface $input)
409
    {
410
        $kernel = $this->getContainer()->get('kernel');
411
412
        // mandatory args and options
413
        $builderArgs = array(
414
            $_SERVER['argv'][0], // sf console
415
            self::COMMAND_NAME, // name of sf command. Can we get it from the Application instead of hardcoding?
416
            '--env=' . $kernel->getEnvironment(), // sf env
417
            '--child'
418
        );
419
        // sf/ez env options
420
        if (!$kernel->isDebug()) {
421
            $builderArgs[] = '--no-debug';
422
        }
423
        if ($input->getOption('siteaccess')) {
424
            $builderArgs[]='--siteaccess='.$input->getOption('siteaccess');
425
        }
426
        // 'optional' options
427
        // note: options 'clear-cache', 'ignore-failures', 'no-interaction', 'path' and 'separate-process' we never propagate
428
        if ($input->getOption('admin-login')) {
429
            $builderArgs[] = '--admin-login=' . $input->getOption('admin-login');
430
        }
431
        if ($input->getOption('default-language')) {
432
            $builderArgs[] = '--default-language=' . $input->getOption('default-language');
433
        }
434
        if ($input->getOption('force')) {
435
            $builderArgs[] = '--force';
436
        }
437
        if ($input->getOption('no-transactions')) {
438
            $builderArgs[] = '--no-transactions';
439
        }
440
        // useful in case the subprocess has a migration step of type process/run
441
        if ($input->getOption('force-sigchild-handling')) {
442
            $builderArgs[] = '--force-sigchild-handling';
443
        }
444
445
        return $builderArgs;
446
    }
447
}
448