MigrateExecutable.php 15.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\migrate\MigrateExecutable.
 */

namespace Drupal\migrate;

10
use Drupal\Core\Utility\Error;
11
use Drupal\Core\StringTranslation\StringTranslationTrait;
12
use Drupal\migrate\Entity\MigrationInterface;
13 14 15 16
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\migrate\Event\MigratePostRowSaveEvent;
use Drupal\migrate\Event\MigratePreRowSaveEvent;
17
use Drupal\migrate\Exception\RequirementsException;
18
use Drupal\migrate\Plugin\MigrateIdMapInterface;
19
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
20 21 22 23

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

  /**
28
   * The configuration of the migration to do.
29
   *
30
   * @var \Drupal\migrate\Entity\Migration
31 32 33 34 35 36 37 38 39 40 41
   */
  protected $migration;

  /**
   * Status of one row.
   *
   * The value is a MigrateIdMapInterface::STATUS_* constant, for example:
   * STATUS_IMPORTED.
   *
   * @var int
   */
42
  protected $sourceRowStatus;
43 44 45 46 47 48 49 50 51 52 53 54

  /**
   * The queued messages not yet saved.
   *
   * Each element in the array is an array with two keys:
   * - 'message': The message string.
   * - 'level': The level, a MigrationInterface::MESSAGE_* constant.
   *
   * @var array
   */
  protected $queuedMessages = array();

55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /**
   * 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;

69 70
  /**
   * The configuration values of the source.
71
   *
72
   * @var array
73
   */
74 75
  protected $sourceIdValues;

76
  /**
77
   * The rollback action to be saved for the current row.
78 79 80
   *
   * @var int
   */
81
  public $rollbackAction;
82 83

  /**
84
   * An array of counts. Initially used for cache hit/miss tracking.
85
   *
86 87
   * @var array
   */
88
  protected $counts = array();
89 90

  /**
91 92 93
   * The maximum number of items to pass in a single call during a rollback.
   *
   * For use in bulkRollback(). Can be overridden in derived class constructor.
94
   *
95 96
   * @var int
   */
97
  protected $rollbackBatchSize = 50;
98 99

  /**
100
   * The object currently being constructed.
101
   *
102
   * @var \stdClass
103
   */
104 105 106 107 108
  protected $destinationValues;

  /**
   * The source.
   *
109
   * @var \Drupal\migrate\Plugin\MigrateSourceInterface
110 111 112 113 114 115 116 117 118
   */
  protected $source;

  /**
   * The current data row retrieved from the source.
   *
   * @var \stdClass
   */
  protected $sourceValues;
119

120 121 122 123 124 125 126
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

127
  /**
128 129 130 131 132 133
   * Constructs a MigrateExecutable and verifies and sets the memory limit.
   *
   * @param \Drupal\migrate\Entity\MigrationInterface $migration
   *   The migration to run.
   * @param \Drupal\migrate\MigrateMessageInterface $message
   *   The message to record.
134 135
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
136 137 138
   *
   * @throws \Drupal\migrate\MigrateException
   */
139
  public function __construct(MigrationInterface $migration, MigrateMessageInterface $message, EventDispatcherInterface $event_dispatcher = NULL) {
140 141 142
    $this->migration = $migration;
    $this->message = $message;
    $this->migration->getIdMap()->setMessage($message);
143
    $this->eventDispatcher = $event_dispatcher;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    // 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;
            $this->message->display($this->t('Invalid PHP memory_limit !limit, setting to unlimited.',
              array('!limit' => $limit)));
        }
      }
      $this->memoryLimit = $limit;
    }
168 169 170
  }

  /**
171 172 173 174
   * Returns the source.
   *
   * Makes sure source is initialized based on migration settings.
   *
175
   * @return \Drupal\migrate\Plugin\MigrateSourceInterface
176
   *   The source.
177
   */
178
  protected function getSource() {
179
    if (!isset($this->source)) {
180 181 182
      $this->source = $this->migration->getSourcePlugin();

      // @TODO, find out how to remove this.
183
      // @see https://www.drupal.org/node/2443617
184
      $this->source->migrateExecutable = $this;
185 186 187 188
    }
    return $this->source;
  }

189 190 191 192 193 194 195 196 197 198 199 200
  /**
   * Gets the event dispatcher.
   *
   * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected function getEventDispatcher() {
    if (!$this->eventDispatcher) {
      $this->eventDispatcher = \Drupal::service('event_dispatcher');
    }
    return $this->eventDispatcher;
  }

201
  /**
202
   * {@inheritdoc}
203 204
   */
  public function import() {
205 206 207 208 209 210 211 212 213
    // 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;
    }
214 215
    $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_IMPORT, new MigrateImportEvent($this->migration));

216
    // Knock off migration if the requirements haven't been met.
217 218 219 220
    try {
      $this->migration->checkRequirements();
    }
    catch (RequirementsException $e) {
221
      $this->message->display(
222 223 224 225 226
        $this->t('Migration @id did not meet the requirements. @message @requirements', array(
          '@id' => $this->migration->id(),
          '@message' => $e->getMessage(),
          '@requirements' => $e->getRequirementsString(),
        )), 'error');
227 228
      return MigrationInterface::RESULT_FAILED;
    }
229

230
    $this->migration->setStatus(MigrationInterface::STATUS_IMPORTING);
231 232 233 234 235 236 237 238 239
    $return = MigrationInterface::RESULT_COMPLETED;
    $source = $this->getSource();
    $id_map = $this->migration->getIdMap();

    try {
      $source->rewind();
    }
    catch (\Exception $e) {
      $this->message->display(
240
        $this->t('Migration failed with source plugin exception: !e', array('!e' => $e->getMessage())), 'error');
241
      $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
242 243
      return MigrationInterface::RESULT_FAILED;
    }
244

245
    $destination = $this->migration->getDestinationPlugin();
246 247 248 249
    while ($source->valid()) {
      $row = $source->current();
      if ($this->sourceIdValues = $row->getSourceIdValues()) {
        // Wipe old messages, and save any new messages.
250
        $id_map->delete($this->sourceIdValues, TRUE);
251 252 253 254
        $this->saveQueuedMessages();
      }

      try {
255 256
        $this->processRow($row);
        $save = TRUE;
257
      }
258 259 260
      catch (MigrateSkipRowException $e) {
        $id_map->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_IGNORED, $this->rollbackAction);
        $save = FALSE;
261
      }
262 263 264

      if ($save) {
        try {
265
          $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROW_SAVE, new MigratePreRowSaveEvent($this->migration, $row));
266
          $destination_id_values = $destination->import($row, $id_map->lookupDestinationId($this->sourceIdValues));
267
          $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROW_SAVE, new MigratePostRowSaveEvent($this->migration, $row, $destination_id_values));
268
          if ($destination_id_values) {
269 270 271 272
            // We do not save an idMap entry for config.
            if ($destination_id_values !== TRUE) {
              $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $this->rollbackAction);
            }
273 274 275 276 277 278 279 280 281 282 283 284 285
          }
          else {
            $id_map->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_FAILED, $this->rollbackAction);
            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) {
          $this->migration->getIdMap()->saveIdMapping($row, array(), $e->getStatus(), $this->rollbackAction);
          $this->saveMessage($e->getMessage(), $e->getLevel());
286
          $this->message->display($e->getMessage(), 'error');
287 288 289 290 291
        }
        catch (\Exception $e) {
          $this->migration->getIdMap()->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_FAILED, $this->rollbackAction);
          $this->handleException($e);
        }
292
      }
293 294
      if ($high_water_property = $this->migration->get('highWaterProperty')) {
        $this->migration->saveHighWater($row->getSourceProperty($high_water_property['name']));
295 296 297 298
      }

      // Reset row properties.
      unset($sourceValues, $destinationValues);
299
      $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
300

301 302 303 304
      if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
        break;
      }

305 306 307 308 309 310
      try {
        $source->next();
      }
      catch (\Exception $e) {
        $this->message->display(
          $this->t('Migration failed with source plugin exception: !e',
311
            array('!e' => $e->getMessage())), 'error');
312
        $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
313 314 315 316
        return MigrationInterface::RESULT_FAILED;
      }
    }

317
    $this->migration->setMigrationResult($return);
318
    $this->getEventDispatcher()->dispatch(MigrateEvents::POST_IMPORT, new MigrateImportEvent($this->migration));
319
    $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
320 321 322 323
    return $return;
  }

  /**
324
   * {@inheritdoc}
325 326 327
   */
  public function processRow(Row $row, array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
328
      $multiple = FALSE;
329
      /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
330
      foreach ($plugins as $plugin) {
331 332 333 334 335 336 337 338 339 340
        $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));
          }
341
          $break = FALSE;
342
          foreach ($value as $scalar_value) {
343 344 345 346 347 348
            try {
              $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
            }
            catch (MigrateSkipProcessException $e) {
              $break = TRUE;
            }
349 350
          }
          $value = $new_value;
351 352 353
          if ($break) {
            break;
          }
354 355
        }
        else {
356 357 358 359 360 361
          try {
            $value = $plugin->transform($value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
            break;
          }
362 363
          $multiple = $multiple || $plugin->multiple();
        }
364
      }
365 366 367 368
      // No plugins means do not set.
      if ($plugins) {
        $row->setDestinationProperty($destination, $value);
      }
369 370 371 372 373 374
      // Reset the value.
      $value = NULL;
    }
  }

  /**
375
   * Fetches the key array for the current source record.
376 377
   *
   * @return array
378
   *   The current source IDs.
379 380 381 382 383 384
   */
  protected function currentSourceIds() {
    return $this->getSource()->getCurrentIds();
  }

  /**
385
   * {@inheritdoc}
386 387 388 389 390 391
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->migration->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  }

  /**
392
   * {@inheritdoc}
393 394 395 396 397 398
   */
  public function queueMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->queuedMessages[] = array('message' => $message, 'level' => $level);
  }

  /**
399
   * {@inheritdoc}
400 401 402 403 404 405 406 407
   */
  public function saveQueuedMessages() {
    foreach ($this->queuedMessages as $queued_message) {
      $this->saveMessage($queued_message['message'], $queued_message['level']);
    }
    $this->queuedMessages = array();
  }

408 409 410 411
  /**
   * Takes an Exception object and both saves and displays it.
   *
   * Pulls in additional information on the location triggering the exception.
412 413
   *
   * @param \Exception $exception
414 415 416 417
   *   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.
418
   */
419
  protected function handleException(\Exception $exception, $save = TRUE) {
420
    $result = Error::decodeException($exception);
421
    $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
422 423 424
    if ($save) {
      $this->saveMessage($message);
    }
425
    $this->message->display($message, 'error');
426 427
  }

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 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 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  /**
   * 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(
        $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');
      $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(
          $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');
        return TRUE;
      }
      else {
        $this->message->display(
          $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))),
          '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();
    // @TODO: explore resetting the container.
    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);
  }

524
}