MigrateExecutable.php 18.2 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\migrate;

5
use Drupal\Component\Utility\Bytes;
6
use Drupal\Core\Utility\Error;
7
use Drupal\Core\StringTranslation\StringTranslationTrait;
8 9 10 11
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\migrate\Event\MigratePostRowSaveEvent;
use Drupal\migrate\Event\MigratePreRowSaveEvent;
12 13
use Drupal\migrate\Event\MigrateRollbackEvent;
use Drupal\migrate\Event\MigrateRowDeleteEvent;
14
use Drupal\migrate\Exception\RequirementsException;
15
use Drupal\migrate\Plugin\MigrateIdMapInterface;
16
use Drupal\migrate\Plugin\MigrationInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18 19 20 21

/**
 * Defines a migrate executable class.
 */
22
class MigrateExecutable implements MigrateExecutableInterface {
23
  use StringTranslationTrait;
24 25

  /**
26
   * The configuration of the migration to do.
27
   *
28
   * @var \Drupal\migrate\Plugin\MigrationInterface
29 30 31 32 33 34 35 36 37 38 39
   */
  protected $migration;

  /**
   * Status of one row.
   *
   * The value is a MigrateIdMapInterface::STATUS_* constant, for example:
   * STATUS_IMPORTED.
   *
   * @var int
   */
40
  protected $sourceRowStatus;
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55
  /**
   * The ratio of the memory limit at which an operation will be interrupted.
   *
   * @var float
   */
  protected $memoryThreshold = 0.85;

  /**
   * The PHP memory_limit expressed in bytes.
   *
   * @var int
   */
  protected $memoryLimit;

56 57
  /**
   * The configuration values of the source.
58
   *
59
   * @var array
60
   */
61 62
  protected $sourceIdValues;

63
  /**
64
   * An array of counts. Initially used for cache hit/miss tracking.
65
   *
66 67
   * @var array
   */
68
  protected $counts = [];
69

70 71 72
  /**
   * The source.
   *
73
   * @var \Drupal\migrate\Plugin\MigrateSourceInterface
74 75 76
   */
  protected $source;

77 78 79 80 81 82 83
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

84 85 86 87 88 89 90 91 92
  /**
   * Migration message service.
   *
   * @todo https://www.drupal.org/node/2822663 Make this protected.
   *
   * @var \Drupal\migrate\MigrateMessageInterface
   */
  public $message;

93
  /**
94 95
   * Constructs a MigrateExecutable and verifies and sets the memory limit.
   *
96
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
97 98
   *   The migration to run.
   * @param \Drupal\migrate\MigrateMessageInterface $message
99
   *   (optional) The migrate message service.
100
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
101
   *   (optional) The event dispatcher.
102 103 104
   *
   * @throws \Drupal\migrate\MigrateException
   */
105
  public function __construct(MigrationInterface $migration, MigrateMessageInterface $message = NULL, EventDispatcherInterface $event_dispatcher = NULL) {
106
    $this->migration = $migration;
107
    $this->message = $message ?: new MigrateMessage();
108
    $this->getIdMap()->setMessage($this->message);
109
    $this->eventDispatcher = $event_dispatcher;
110 111 112 113 114 115
    // Record the memory limit in bytes
    $limit = trim(ini_get('memory_limit'));
    if ($limit == '-1') {
      $this->memoryLimit = PHP_INT_MAX;
    }
    else {
116
      $this->memoryLimit = Bytes::toInt($limit);
117
    }
118 119 120
  }

  /**
121 122 123 124
   * Returns the source.
   *
   * Makes sure source is initialized based on migration settings.
   *
125
   * @return \Drupal\migrate\Plugin\MigrateSourceInterface
126
   *   The source.
127
   */
128
  protected function getSource() {
129
    if (!isset($this->source)) {
130
      $this->source = $this->migration->getSourcePlugin();
131 132 133 134
    }
    return $this->source;
  }

135 136 137 138 139 140 141 142 143 144 145 146
  /**
   * Gets the event dispatcher.
   *
   * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected function getEventDispatcher() {
    if (!$this->eventDispatcher) {
      $this->eventDispatcher = \Drupal::service('event_dispatcher');
    }
    return $this->eventDispatcher;
  }

147
  /**
148
   * {@inheritdoc}
149 150
   */
  public function import() {
151 152 153
    // Only begin the import operation if the migration is currently idle.
    if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
      $this->message->display($this->t('Migration @id is busy with another operation: @status',
154
        [
155 156
          '@id' => $this->migration->id(),
          '@status' => $this->t($this->migration->getStatusLabel()),
157
        ]), 'error');
158 159
      return MigrationInterface::RESULT_FAILED;
    }
160
    $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_IMPORT, new MigrateImportEvent($this->migration, $this->message));
161

162
    // Knock off migration if the requirements haven't been met.
163
    try {
164
      $this->migration->checkRequirements();
165 166
    }
    catch (RequirementsException $e) {
167
      $this->message->display(
168 169
        $this->t(
          'Migration @id did not meet the requirements. @message @requirements',
170
          [
171 172 173
            '@id' => $this->migration->id(),
            '@message' => $e->getMessage(),
            '@requirements' => $e->getRequirementsString(),
174
          ]
175 176 177 178
        ),
        'error'
      );

179 180
      return MigrationInterface::RESULT_FAILED;
    }
181

182
    $this->migration->setStatus(MigrationInterface::STATUS_IMPORTING);
183 184
    $return = MigrationInterface::RESULT_COMPLETED;
    $source = $this->getSource();
185
    $id_map = $this->getIdMap();
186 187 188 189 190 191

    try {
      $source->rewind();
    }
    catch (\Exception $e) {
      $this->message->display(
192
        $this->t('Migration failed with source plugin exception: @e', ['@e' => $e->getMessage()]), 'error');
193
      $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
194 195
      return MigrationInterface::RESULT_FAILED;
    }
196

197
    $destination = $this->migration->getDestinationPlugin();
198 199
    while ($source->valid()) {
      $row = $source->current();
200
      $this->sourceIdValues = $row->getSourceIdValues();
201 202

      try {
203 204
        $this->processRow($row);
        $save = TRUE;
205
      }
206
      catch (MigrateException $e) {
207
        $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
208 209 210
        $this->saveMessage($e->getMessage(), $e->getLevel());
        $save = FALSE;
      }
211
      catch (MigrateSkipRowException $e) {
212 213 214
        if ($e->getSaveToMap()) {
          $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_IGNORED);
        }
215 216 217
        if ($message = trim($e->getMessage())) {
          $this->saveMessage($message, MigrationInterface::MESSAGE_INFORMATIONAL);
        }
218
        $save = FALSE;
219
      }
220 221 222

      if ($save) {
        try {
223
          $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROW_SAVE, new MigratePreRowSaveEvent($this->migration, $this->message, $row));
224 225 226
          $destination_ids = $id_map->lookupDestinationIds($this->sourceIdValues);
          $destination_id_values = $destination_ids ? reset($destination_ids) : [];
          $destination_id_values = $destination->import($row, $destination_id_values);
227
          $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROW_SAVE, new MigratePostRowSaveEvent($this->migration, $this->message, $row, $destination_id_values));
228
          if ($destination_id_values) {
229 230
            // We do not save an idMap entry for config.
            if ($destination_id_values !== TRUE) {
231
              $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $destination->rollbackAction());
232
            }
233 234
          }
          else {
235
            $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
236 237 238 239 240 241 242 243
            if (!$id_map->messageCount()) {
              $message = $this->t('New object was not saved, no error provided');
              $this->saveMessage($message);
              $this->message->display($message);
            }
          }
        }
        catch (MigrateException $e) {
244
          $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
245 246 247
          $this->saveMessage($e->getMessage(), $e->getLevel());
        }
        catch (\Exception $e) {
248
          $this->getIdMap()->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
249 250
          $this->handleException($e);
        }
251 252
      }

253
      $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
254

255
      // Check for memory exhaustion.
256 257 258 259
      if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
        break;
      }

260 261
      // If anyone has requested we stop, return the requested result.
      if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
262 263
        $return = $this->migration->getInterruptionResult();
        $this->migration->clearInterruptionResult();
264 265 266
        break;
      }

267 268 269 270 271
      try {
        $source->next();
      }
      catch (\Exception $e) {
        $this->message->display(
272
          $this->t('Migration failed with source plugin exception: @e',
273
            ['@e' => $e->getMessage()]), 'error');
274
        $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
275 276 277 278
        return MigrationInterface::RESULT_FAILED;
      }
    }

279
    $this->getEventDispatcher()->dispatch(MigrateEvents::POST_IMPORT, new MigrateImportEvent($this->migration, $this->message));
280
    $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
281 282 283
    return $return;
  }

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  /**
   * {@inheritdoc}
   */
  public function rollback() {
    // Only begin the rollback operation if the migration is currently idle.
    if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
      $this->message->display($this->t('Migration @id is busy with another operation: @status', ['@id' => $this->migration->id(), '@status' => $this->t($this->migration->getStatusLabel())]), 'error');
      return MigrationInterface::RESULT_FAILED;
    }

    // Announce that rollback is about to happen.
    $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROLLBACK, new MigrateRollbackEvent($this->migration));

    // Optimistically assume things are going to work out; if not, $return will be
    // updated to some other status.
    $return = MigrationInterface::RESULT_COMPLETED;

    $this->migration->setStatus(MigrationInterface::STATUS_ROLLING_BACK);
302
    $id_map = $this->getIdMap();
303 304 305
    $destination = $this->migration->getDestinationPlugin();

    // Loop through each row in the map, and try to roll it back.
306 307
    $id_map->rewind();
    while ($id_map->valid()) {
308 309
      $destination_key = $id_map->currentDestination();
      if ($destination_key) {
310 311 312 313 314 315 316 317
        $map_row = $id_map->getRowByDestination($destination_key);
        if ($map_row['rollback_action'] == MigrateIdMapInterface::ROLLBACK_DELETE) {
          $this->getEventDispatcher()
            ->dispatch(MigrateEvents::PRE_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
          $destination->rollback($destination_key);
          $this->getEventDispatcher()
            ->dispatch(MigrateEvents::POST_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
        }
318
        // We're now done with this row, so remove it from the map.
319
        $id_map->deleteDestination($destination_key);
320
      }
321 322 323 324 325 326
      else {
        // If there is no destination key the import probably failed and we can
        // remove the row without further action.
        $source_key = $id_map->currentSource();
        $id_map->delete($source_key);
      }
327
      $id_map->next();
328 329 330 331 332 333 334 335

      // Check for memory exhaustion.
      if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
        break;
      }

      // If anyone has requested we stop, return the requested result.
      if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
336 337
        $return = $this->migration->getInterruptionResult();
        $this->migration->clearInterruptionResult();
338 339 340 341 342 343 344 345 346 347 348
        break;
      }
    }

    // Notify modules that rollback attempt was complete.
    $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROLLBACK, new MigrateRollbackEvent($this->migration));
    $this->migration->setStatus(MigrationInterface::STATUS_IDLE);

    return $return;
  }

349 350 351 352 353 354 355 356 357 358
  /**
   * Get the ID map from the current migration.
   *
   * @return \Drupal\migrate\Plugin\MigrateIdMapInterface
   *   The ID map.
   */
  protected function getIdMap() {
    return $this->migration->getIdMap();
  }

359
  /**
360
   * {@inheritdoc}
361 362 363
   */
  public function processRow(Row $row, array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
364
      $multiple = FALSE;
365
      /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
366
      foreach ($plugins as $plugin) {
367 368 369 370 371 372
        $definition = $plugin->getPluginDefinition();
        // Many plugins expect a scalar value but the current value of the
        // pipeline might be multiple scalars (this is set by the previous
        // plugin) and in this case the current value needs to be iterated
        // and each scalar separately transformed.
        if ($multiple && !$definition['handle_multiples']) {
373
          $new_value = [];
374
          if (!is_array($value)) {
375
            throw new MigrateException(sprintf('Pipeline failed at %s plugin for destination %s: %s received instead of an array,', $plugin->getPluginId(), $destination, $value));
376
          }
377
          $break = FALSE;
378
          foreach ($value as $scalar_value) {
379 380 381 382
            try {
              $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
            }
            catch (MigrateSkipProcessException $e) {
383
              $new_value[] = NULL;
384 385
              $break = TRUE;
            }
386 387
          }
          $value = $new_value;
388 389 390
          if ($break) {
            break;
          }
391 392
        }
        else {
393 394 395 396
          try {
            $value = $plugin->transform($value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
397
            $value = NULL;
398 399
            break;
          }
400
          $multiple = $plugin->multiple();
401
        }
402
      }
403 404 405 406 407 408 409 410
      // Ensure all values, including nulls, are migrated.
      if ($plugins) {
        if (isset($value)) {
          $row->setDestinationProperty($destination, $value);
        }
        else {
          $row->setEmptyDestinationProperty($destination);
        }
411
      }
412 413 414 415 416 417
      // Reset the value.
      $value = NULL;
    }
  }

  /**
418
   * Fetches the key array for the current source record.
419 420
   *
   * @return array
421
   *   The current source IDs.
422 423 424 425 426 427
   */
  protected function currentSourceIds() {
    return $this->getSource()->getCurrentIds();
  }

  /**
428
   * {@inheritdoc}
429 430
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
431
    $this->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
432 433
  }

434 435 436 437
  /**
   * Takes an Exception object and both saves and displays it.
   *
   * Pulls in additional information on the location triggering the exception.
438 439
   *
   * @param \Exception $exception
440 441 442 443
   *   Object representing the exception.
   * @param bool $save
   *   (optional) Whether to save the message in the migration's mapping table.
   *   Set to FALSE in contexts where this doesn't make sense.
444
   */
445
  protected function handleException(\Exception $exception, $save = TRUE) {
446
    $result = Error::decodeException($exception);
447
    $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
448 449 450
    if ($save) {
      $this->saveMessage($message);
    }
451
    $this->message->display($message, 'error');
452 453
  }

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  /**
   * Checks for exceptional conditions, and display feedback.
   */
  protected function checkStatus() {
    if ($this->memoryExceeded()) {
      return MigrationInterface::RESULT_INCOMPLETE;
    }
    return MigrationInterface::RESULT_COMPLETED;
  }

  /**
   * Tests whether we've exceeded the desired memory threshold.
   *
   * If so, output a message.
   *
   * @return bool
   *   TRUE if the threshold is exceeded, otherwise FALSE.
   */
  protected function memoryExceeded() {
    $usage = $this->getMemoryUsage();
    $pct_memory = $usage / $this->memoryLimit;
    if (!$threshold = $this->memoryThreshold) {
      return FALSE;
    }
    if ($pct_memory > $threshold) {
      $this->message->display(
480 481
        $this->t(
          'Memory usage is @usage (@pct% of limit @limit), reclaiming memory.',
482
          [
483 484 485
            '@pct' => round($pct_memory * 100),
            '@usage' => $this->formatSize($usage),
            '@limit' => $this->formatSize($this->memoryLimit),
486
          ]
487 488 489
        ),
        'warning'
      );
490 491 492 493 494 495
      $usage = $this->attemptMemoryReclaim();
      $pct_memory = $usage / $this->memoryLimit;
      // Use a lower threshold - we don't want to be in a situation where we keep
      // coming back here and trimming a tiny amount
      if ($pct_memory > (0.90 * $threshold)) {
        $this->message->display(
496 497
          $this->t(
            'Memory usage is now @usage (@pct% of limit @limit), not enough reclaimed, starting new batch',
498
            [
499 500 501
              '@pct' => round($pct_memory * 100),
              '@usage' => $this->formatSize($usage),
              '@limit' => $this->formatSize($this->memoryLimit),
502
            ]
503 504 505
          ),
          'warning'
        );
506 507 508 509
        return TRUE;
      }
      else {
        $this->message->display(
510 511
          $this->t(
            'Memory usage is now @usage (@pct% of limit @limit), reclaimed enough, continuing',
512
            [
513 514 515
              '@pct' => round($pct_memory * 100),
              '@usage' => $this->formatSize($usage),
              '@limit' => $this->formatSize($this->memoryLimit),
516
            ]
517
          ),
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
          'warning');
        return FALSE;
      }
    }
    else {
      return FALSE;
    }
  }

  /**
   * Returns the memory usage so far.
   *
   * @return int
   *   The memory usage.
   */
  protected function getMemoryUsage() {
    return memory_get_usage();
  }

  /**
   * Tries to reclaim memory.
   *
   * @return int
   *   The memory usage after reclaim.
   */
  protected function attemptMemoryReclaim() {
    // First, try resetting Drupal's static storage - this frequently releases
    // plenty of memory to continue.
    drupal_static_reset();
547 548

    // Entity storage can blow up with caches so clear them out.
549
    $manager = \Drupal::entityManager();
550 551 552 553
    foreach ($manager->getDefinitions() as $id => $definition) {
      $manager->getStorage($id)->resetCache();
    }

554
    // @TODO: explore resetting the container.
555

556 557 558
    // Run garbage collector to further reduce memory.
    gc_collect_cycles();

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    return memory_get_usage();
  }

  /**
   * Generates a string representation for the given byte count.
   *
   * @param int $size
   *   A size in bytes.
   *
   * @return string
   *   A translated string representation of the size.
   */
  protected function formatSize($size) {
    return format_size($size);
  }

575
}