Passed
Push — master ( 15b42a...339444 )
by Gaetano
09:53
created

MigrateCommand   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 434
Duplicated Lines 0 %

Test Coverage

Coverage 54.07%

Importance

Changes 0
Metric Value
eloc 219
dl 0
loc 434
rs 3.6
c 0
b 0
f 0
ccs 106
cts 196
cp 0.5407
wmc 60

8 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 21 1
F execute() 0 133 20
B createChildProcessArgs() 0 38 8
A askForConfirmation() 0 20 5
A executeMigrationInProcess() 0 8 1
A printMigrationsList() 0 25 4
B buildMigrationsList() 0 37 11
B executeMigrationInSeparateProcess() 0 67 10

How to fix   Complexity   

Complex Class

Complex classes like MigrateCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MigrateCommand, and based on these observations, apply Extract Interface, too.

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

98
        $toExecute = $this->buildMigrationsList(/** @scrutinizer ignore-type */ $input->getOption('path'), $migrationService, $force);
Loading history...
99
100
        if (!count($toExecute)) {
101 47
            $output->writeln('<info>No migrations to execute</info>');
102
            return 0;
103
        }
104
105 47
        $this->printMigrationsList($toExecute, $input, $output);
106
107
        // ask user for confirmation to make changes
108
        if (!$this->askForConfirmation($input, $output)) {
109
            return 0;
110
        }
111
112
        if ($input->getOption('separate-process')) {
113
            $builder = new ProcessBuilder();
114 47
            $executableFinder = new PhpExecutableFinder();
115 47
            if (false !== $php = $executableFinder->find()) {
116 47
                $builder->setPrefix($php);
117
            }
118
            $builderArgs = $this->createChildProcessArgs($input);
119 47
        }
120
121
        // allow forcing handling of sigchild. Useful on eg. Debian and Ubuntu
122 47
        if ($input->getOption('force-sigchild-enabled')) {
123 9
            Process::forceSigchildEnabled(true);
124 9
        }
125 9
126
        $aborting = false;
127
        $total = count($toExecute);
128 38
        $executed = 0;
129
        $failed = 0;
130 38
        $skipped = 0;
131
132
        /** @var MigrationDefinition $migrationDefinition */
133
        foreach ($toExecute as $name => $migrationDefinition) {
134
135
            // let's skip migrations that we know are invalid - user was warned and he decided to proceed anyway
136
            if ($migrationDefinition->status == MigrationDefinition::STATUS_INVALID) {
137
                $output->writeln("<comment>Skipping $name</comment>\n");
138
                $skipped++;
139
                continue;
140
            }
141
142
            $this->writeln("<info>Processing $name</info>");
143
144
            if ($input->getOption('separate-process')) {
145
146
                try {
147
                    /// @todo in quiet mode, we could suppress output of the sub-command...
148
                    $this->executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs, true);
0 ignored issues
show
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...
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...
149
150
                    $executed++;
151
                } catch (\Exception $e) {
152
                    $failed++;
153 38
154
155 30
                    $errorMessage = $e->getMessage();
156 8
                    // we probably have already echoed the error message while the subprocess was executing, avoid repeating it
157 8
                    if ($errorMessage != $this->subProcessErrorString) {
158
                        if ($e instanceof AfterMigrationExecutionException) {
159
                            $errorMessage = "Failure after migration end! Reason: " . $errorMessage;
160
                        } else {
161
                            $errorMessage = "Migration failed! Reason: " . $errorMessage;
162 8
                        }
163 38
164
                        $this->errOutput->writeln("\n<error>$errorMessage</error>");
165
                    }
166
167
                    if (!$input->getOption('ignore-failures')) {
168
                        $this->errOutput->writeln("\n<error>Migration execution aborted</error>");
169 39
                        $aborting = true;
170
                        break;
171
                    }
172
                }
173
174
            } else {
175 39
176 39
                try {
177 39
                    $this->executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input);
178
179
                    $executed++;
180
                } catch (\Exception $e) {
181 39
                    $failed++;
182
183 39
                    $this->errOutput->writeln("\n<error>Migration failed! Reason: " . $e->getMessage() . "</error>");
184
185 38
                    if (!$input->getOption('ignore-failures')) {
186
                        $this->writeErrorln("\n<error>Migration execution aborted</error>");
187 38
                        $aborting = true;
188 38
                        break;
189 38
                    }
190 38
                }
191 38
192 38
            }
193
        }
194 30
195
        if ($input->getOption('clear-cache') && !$aborting) {
196
            $command = $this->getApplication()->find('cache:clear');
197
            $inputArray = new ArrayInput(array('command' => 'cache:clear'));
198
            $command->run($inputArray, $output);
199
        }
200
201
202
        $missed = $total - $executed - $failed - $skipped;
203
204
        $time = microtime(true) - $start;
205
        $this->writeln("Executed $executed migrations, failed $failed, skipped $skipped" . ($missed ? ", missed $missed" : ''));
206
        if ($input->getOption('separate-process')) {
207
            // in case of using subprocesses, we can not measure max memory used
208
            $this->writeln("Time taken: ".sprintf('%.2f', $time)." secs");
209
        } else {
210
            $this->writeln("Time taken: ".sprintf('%.2f', $time)." secs, memory: ".sprintf('%.2f', (memory_get_peak_usage(true) / 1000000)). ' MB');
211
        }
212
213
        return $failed;
214
    }
215
216
    /**
217
     * @param MigrationDefinition $migrationDefinition
218
     * @param bool $force
219
     * @param MigrationService $migrationService
220
     * @param InputInterface $input
221
     */
222
    protected function executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input)
223
    {
224
        $migrationService->executeMigration(
225
            $migrationDefinition,
226
            !$input->getOption('no-transactions'),
227
            $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

227
            /** @scrutinizer ignore-type */ $input->getOption('default-language'),
Loading history...
228
            $input->getOption('admin-login'),
229
            $force
230
        );
231
    }
232
233
    /**
234
     * @param MigrationDefinition $migrationDefinition
235
     * @param MigrationService $migrationService
236
     * @param ProcessBuilder $builder
237
     * @param array $builderArgs
238
     * @param bool $feedback
239
     */
240
    protected function executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs, $feedback = true)
241
    {
242
        $process = $builder
243
            ->setArguments(array_merge($builderArgs, array('--path=' . $migrationDefinition->path)))
244
            ->getProcess();
245
246
        if ($feedback) {
247
            $this->writeln('<info>Executing: ' . $process->getCommandLine() . '</info>', OutputInterface::VERBOSITY_VERBOSE);
248
        }
249
250
        $this->subProcessErrorString = '';
251
252
        // allow long migrations processes by default
253 47
        $process->setTimeout($this->subProcessTimeout);
254
255 47
        // and give immediate feedback to the user...
256 47
        // NB: if the subprocess writes to stderr then terminates with non-0 exit code, this will lead us to echoing the
257
        // error text twice, once here and once at the end of execution of this command.
258 47
        // In order to avoid that, since we can not know at this time what the subprocess exit code will be, we should
259 47
        // somehow still print the error text now, and compare it to what we gt at the end...
260
        $process->run(
261
            $feedback ?
262
                function($type, $buffer) {
263
                    if ($type == 'err') {
264 47
                        $this->subProcessErrorString .= $buffer;
265 47
                        $this->errOutput->write($buffer, OutputInterface::OUTPUT_RAW);
0 ignored issues
show
Bug introduced by
Symfony\Component\Consol...utInterface::OUTPUT_RAW of type integer is incompatible with the type boolean expected by parameter $newline of Symfony\Component\Consol...utputInterface::write(). ( Ignorable by Annotation )

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

265
                        $this->errOutput->write($buffer, /** @scrutinizer ignore-type */ OutputInterface::OUTPUT_RAW);
Loading history...
266 47
                    } else {
267 47
                        $this->output->write($buffer, OutputInterface::OUTPUT_RAW);
268
                    }
269
                }
270
                :
271
                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

271
                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

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

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