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

namespace Drupal\migrate;

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

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

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

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

41 42 43 44 45 46 47 48 49 50 51 52 53 54
  /**
   * 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;

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

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

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

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

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

92
  /**
93 94
   * Constructs a MigrateExecutable and verifies and sets the memory limit.
   *
95
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
96 97 98
   *   The migration to run.
   * @param \Drupal\migrate\MigrateMessageInterface $message
   *   The message to record.
99 100
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
101 102 103
   *
   * @throws \Drupal\migrate\MigrateException
   */
104
  public function __construct(MigrationInterface $migration, MigrateMessageInterface $message, EventDispatcherInterface $event_dispatcher = NULL) {
105 106 107
    $this->migration = $migration;
    $this->message = $message;
    $this->migration->getIdMap()->setMessage($message);
108
    $this->eventDispatcher = $event_dispatcher;
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    // Record the memory limit in bytes
    $limit = trim(ini_get('memory_limit'));
    if ($limit == '-1') {
      $this->memoryLimit = PHP_INT_MAX;
    }
    else {
      if (!is_numeric($limit)) {
        $last = strtolower(substr($limit, -1));
        switch ($last) {
          case 'g':
            $limit *= 1024;
          case 'm':
            $limit *= 1024;
          case 'k':
            $limit *= 1024;
            break;
          default:
            $limit = PHP_INT_MAX;
127 128
            $this->message->display($this->t('Invalid PHP memory_limit @limit, setting to unlimited.',
              array('@limit' => $limit)));
129 130 131 132
        }
      }
      $this->memoryLimit = $limit;
    }
133 134 135
  }

  /**
136 137 138 139
   * Returns the source.
   *
   * Makes sure source is initialized based on migration settings.
   *
140
   * @return \Drupal\migrate\Plugin\MigrateSourceInterface
141
   *   The source.
142
   */
143
  protected function getSource() {
144
    if (!isset($this->source)) {
145
      $this->source = $this->migration->getSourcePlugin();
146 147 148 149
    }
    return $this->source;
  }

150 151 152 153 154 155 156 157 158 159 160 161
  /**
   * Gets the event dispatcher.
   *
   * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected function getEventDispatcher() {
    if (!$this->eventDispatcher) {
      $this->eventDispatcher = \Drupal::service('event_dispatcher');
    }
    return $this->eventDispatcher;
  }

162
  /**
163
   * {@inheritdoc}
164 165
   */
  public function import() {
166 167 168 169 170 171 172 173 174
    // 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',
        array(
          '@id' => $this->migration->id(),
          '@status' => $this->t($this->migration->getStatusLabel()),
        )), 'error');
      return MigrationInterface::RESULT_FAILED;
    }
175
    $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_IMPORT, new MigrateImportEvent($this->migration, $this->message));
176

177
    // Knock off migration if the requirements haven't been met.
178
    try {
179
      $this->migration->checkRequirements();
180 181
    }
    catch (RequirementsException $e) {
182
      $this->message->display(
183 184 185 186 187 188 189 190 191 192 193
        $this->t(
          'Migration @id did not meet the requirements. @message @requirements',
          array(
            '@id' => $this->migration->id(),
            '@message' => $e->getMessage(),
            '@requirements' => $e->getRequirementsString(),
          )
        ),
        'error'
      );

194 195
      return MigrationInterface::RESULT_FAILED;
    }
196

197
    $this->migration->setStatus(MigrationInterface::STATUS_IMPORTING);
198 199 200 201 202 203 204 205 206
    $return = MigrationInterface::RESULT_COMPLETED;
    $source = $this->getSource();
    $id_map = $this->migration->getIdMap();

    try {
      $source->rewind();
    }
    catch (\Exception $e) {
      $this->message->display(
207
        $this->t('Migration failed with source plugin exception: @e', array('@e' => $e->getMessage())), 'error');
208
      $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
209 210
      return MigrationInterface::RESULT_FAILED;
    }
211

212
    $destination = $this->migration->getDestinationPlugin();
213 214
    while ($source->valid()) {
      $row = $source->current();
215
      $this->sourceIdValues = $row->getSourceIdValues();
216 217

      try {
218 219
        $this->processRow($row);
        $save = TRUE;
220
      }
221
      catch (MigrateException $e) {
222
        $this->migration->getIdMap()->saveIdMapping($row, array(), $e->getStatus());
223 224 225
        $this->saveMessage($e->getMessage(), $e->getLevel());
        $save = FALSE;
      }
226
      catch (MigrateSkipRowException $e) {
227 228 229
        if ($e->getSaveToMap()) {
          $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_IGNORED);
        }
230 231 232
        if ($message = trim($e->getMessage())) {
          $this->saveMessage($message, MigrationInterface::MESSAGE_INFORMATIONAL);
        }
233
        $save = FALSE;
234
      }
235 236 237

      if ($save) {
        try {
238
          $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROW_SAVE, new MigratePreRowSaveEvent($this->migration, $this->message, $row));
239
          $destination_id_values = $destination->import($row, $id_map->lookupDestinationId($this->sourceIdValues));
240
          $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROW_SAVE, new MigratePostRowSaveEvent($this->migration, $this->message, $row, $destination_id_values));
241
          if ($destination_id_values) {
242 243
            // We do not save an idMap entry for config.
            if ($destination_id_values !== TRUE) {
244
              $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $destination->rollbackAction());
245
            }
246 247
          }
          else {
248
            $id_map->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_FAILED);
249 250 251 252 253 254 255 256
            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) {
257
          $this->migration->getIdMap()->saveIdMapping($row, array(), $e->getStatus());
258 259 260
          $this->saveMessage($e->getMessage(), $e->getLevel());
        }
        catch (\Exception $e) {
261
          $this->migration->getIdMap()->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_FAILED);
262 263
          $this->handleException($e);
        }
264 265
      }

266
      $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
267

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

273 274
      // If anyone has requested we stop, return the requested result.
      if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
275 276
        $return = $this->migration->getInterruptionResult();
        $this->migration->clearInterruptionResult();
277 278 279
        break;
      }

280 281 282 283 284
      try {
        $source->next();
      }
      catch (\Exception $e) {
        $this->message->display(
285 286
          $this->t('Migration failed with source plugin exception: @e',
            array('@e' => $e->getMessage())), 'error');
287
        $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
288 289 290 291
        return MigrationInterface::RESULT_FAILED;
      }
    }

292
    $this->getEventDispatcher()->dispatch(MigrateEvents::POST_IMPORT, new MigrateImportEvent($this->migration, $this->message));
293
    $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
294 295 296
    return $return;
  }

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  /**
   * {@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);
    $id_map = $this->migration->getIdMap();
    $destination = $this->migration->getDestinationPlugin();

    // Loop through each row in the map, and try to roll it back.
319
    foreach ($id_map as $map_row) {
320 321
      $destination_key = $id_map->currentDestination();
      if ($destination_key) {
322 323 324 325 326 327 328 329
        $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));
        }
330
        // We're now done with this row, so remove it from the map.
331
        $id_map->deleteDestination($destination_key);
332
      }
333 334 335 336 337 338
      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);
      }
339 340 341 342 343 344 345 346

      // 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) {
347 348
        $return = $this->migration->getInterruptionResult();
        $this->migration->clearInterruptionResult();
349 350 351 352 353 354 355 356 357 358 359
        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;
  }

360
  /**
361
   * {@inheritdoc}
362 363 364
   */
  public function processRow(Row $row, array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
365
      $multiple = FALSE;
366
      /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
367
      foreach ($plugins as $plugin) {
368 369 370 371 372 373 374 375 376 377
        $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']) {
          $new_value = array();
          if (!is_array($value)) {
            throw new MigrateException(sprintf('Pipeline failed for destination %s: %s got instead of an array,', $destination, $value));
          }
378
          $break = FALSE;
379
          foreach ($value as $scalar_value) {
380 381 382 383
            try {
              $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
            }
            catch (MigrateSkipProcessException $e) {
384
              $new_value[] = NULL;
385 386
              $break = TRUE;
            }
387 388
          }
          $value = $new_value;
389 390 391
          if ($break) {
            break;
          }
392 393
        }
        else {
394 395 396 397
          try {
            $value = $plugin->transform($value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
398
            $value = NULL;
399 400
            break;
          }
401
          $multiple = $plugin->multiple();
402
        }
403
      }
404 405
      // No plugins or no value means do not set.
      if ($plugins && !is_null($value)) {
406 407
        $row->setDestinationProperty($destination, $value);
      }
408 409 410 411 412 413
      // Reset the value.
      $value = NULL;
    }
  }

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

  /**
424
   * {@inheritdoc}
425 426 427 428 429
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->migration->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  }

430 431 432 433
  /**
   * Takes an Exception object and both saves and displays it.
   *
   * Pulls in additional information on the location triggering the exception.
434 435
   *
   * @param \Exception $exception
436 437 438 439
   *   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.
440
   */
441
  protected function handleException(\Exception $exception, $save = TRUE) {
442
    $result = Error::decodeException($exception);
443
    $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
444 445 446
    if ($save) {
      $this->saveMessage($message);
    }
447
    $this->message->display($message, 'error');
448 449
  }

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  /**
   * 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(
476 477 478 479 480 481 482 483 484 485
        $this->t(
          'Memory usage is @usage (@pct% of limit @limit), reclaiming memory.',
          array(
            '@pct' => round($pct_memory * 100),
            '@usage' => $this->formatSize($usage),
            '@limit' => $this->formatSize($this->memoryLimit),
          )
        ),
        'warning'
      );
486 487 488 489 490 491
      $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(
492 493 494 495 496 497 498 499 500 501
          $this->t(
            'Memory usage is now @usage (@pct% of limit @limit), not enough reclaimed, starting new batch',
            array(
              '@pct' => round($pct_memory * 100),
              '@usage' => $this->formatSize($usage),
              '@limit' => $this->formatSize($this->memoryLimit),
            )
          ),
          'warning'
        );
502 503 504 505
        return TRUE;
      }
      else {
        $this->message->display(
506 507 508 509 510 511 512 513
          $this->t(
            'Memory usage is now @usage (@pct% of limit @limit), reclaimed enough, continuing',
            array(
              '@pct' => round($pct_memory * 100),
              '@usage' => $this->formatSize($usage),
              '@limit' => $this->formatSize($this->memoryLimit),
            )
          ),
514 515 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
          '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();
543 544

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

550
    // @TODO: explore resetting the container.
551

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    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);
  }

568
}