MigrateExecutable.php 17 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
use Drupal\migrate\Exception\RequirementsException;
14 15 16 17 18
use Drupal\migrate\Plugin\MigrateIdMapInterface;

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

  /**
23
   * The configuration of the migration to do.
24
   *
25
   * @var \Drupal\migrate\Entity\Migration
26 27 28 29 30 31 32 33
   */
  protected $migration;

  /**
   * The number of successfully imported rows since feedback was given.
   *
   * @var int
   */
34
  protected $successesSinceFeedback;
35 36 37 38 39 40

  /**
   * The number of rows that were successfully processed.
   *
   * @var int
   */
41
  protected $totalSuccesses;
42 43 44 45 46 47 48 49 50

  /**
   * Status of one row.
   *
   * The value is a MigrateIdMapInterface::STATUS_* constant, for example:
   * STATUS_IMPORTED.
   *
   * @var int
   */
51
  protected $sourceRowStatus;
52 53 54 55 56 57 58 59

  /**
   * The number of rows processed.
   *
   * The total attempted, whether or not they were successful.
   *
   * @var int
   */
60
  protected $totalProcessed;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

  /**
   * 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();

  /**
   * The options that can be set when executing the migration.
   *
   * Values can be set for:
   * - 'limit': Sets a time limit.
   *
   * @var array
   */
  protected $options;

  /**
84
   * The PHP max_execution_time.
85
   *
86 87 88 89
   * @var int
   */
  protected $maxExecTime;

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  /**
   * The ratio of the memory limit at which an operation will be interrupted.
   *
   * @var float
   */
  protected $memoryThreshold = 0.85;

  /**
   * The ratio of the time limit at which an operation will be interrupted.
   *
   * @var float
   */
  public $timeThreshold = 0.90;

  /**
   * The time limit when executing the migration.
   *
   * @var array
   */
  public $limit = array();

111 112
  /**
   * The configuration values of the source.
113
   *
114
   * @var array
115
   */
116 117 118 119 120 121 122 123
  protected $sourceIdValues;

  /**
   * The number of rows processed since feedback was given.
   *
   * @var int
   */
  protected $processedSinceFeedback = 0;
124 125 126 127 128 129 130 131 132

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

  /**
133
   * The rollback action to be saved for the current row.
134 135 136
   *
   * @var int
   */
137
  public $rollbackAction;
138 139

  /**
140
   * An array of counts. Initially used for cache hit/miss tracking.
141
   *
142 143
   * @var array
   */
144
  protected $counts = array();
145 146

  /**
147 148 149
   * 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.
150
   *
151 152
   * @var int
   */
153
  protected $rollbackBatchSize = 50;
154 155

  /**
156
   * The object currently being constructed.
157
   *
158
   * @var \stdClass
159
   */
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  protected $destinationValues;

  /**
   * The source.
   *
   * @var \Drupal\migrate\Source
   */
  protected $source;

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

  /**
177 178 179 180 181 182
   * 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.
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
   *
   * @throws \Drupal\migrate\MigrateException
   */
  public function __construct(MigrationInterface $migration, MigrateMessageInterface $message) {
    $this->migration = $migration;
    $this->message = $message;
    $this->migration->getIdMap()->setMessage($message);
    // 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:
            throw new MigrateException($this->t('Invalid PHP memory_limit !limit',
              array('!limit' => $limit)));
        }
      }
      $this->memoryLimit = $limit;
    }
213 214
    // Record the maximum execution time limit.
    $this->maxExecTime = ini_get('max_execution_time');
215 216 217
  }

  /**
218 219 220 221
   * Returns the source.
   *
   * Makes sure source is initialized based on migration settings.
   *
222
   * @return \Drupal\migrate\Source
223
   *   The source.
224
   */
225
  protected function getSource() {
226 227 228 229 230 231 232
    if (!isset($this->source)) {
      $this->source = new Source($this->migration, $this);
    }
    return $this->source;
  }

  /**
233
   * {@inheritdoc}
234 235
   */
  public function import() {
236
    // Knock off migration if the requirements haven't been met.
237 238 239 240
    try {
      $this->migration->checkRequirements();
    }
    catch (RequirementsException $e) {
241
      $this->message->display(
242 243 244 245 246
        $this->t('Migration @id did not meet the requirements. @message @requirements', array(
          '@id' => $this->migration->id(),
          '@message' => $e->getMessage(),
          '@requirements' => $e->getRequirementsString(),
        )), 'error');
247 248
      return MigrationInterface::RESULT_FAILED;
    }
249

250 251 252 253 254 255 256 257 258 259
    $return = MigrationInterface::RESULT_COMPLETED;
    $source = $this->getSource();
    $id_map = $this->migration->getIdMap();

    try {
      $source->rewind();
    }
    catch (\Exception $e) {
      $this->message->display(
        $this->t('Migration failed with source plugin exception: !e',
260
          array('!e' => $e->getMessage())), 'error');
261 262
      return MigrationInterface::RESULT_FAILED;
    }
263

264 265
    $destination = $this->migration->getDestinationPlugin();

266 267 268 269
    while ($source->valid()) {
      $row = $source->current();
      if ($this->sourceIdValues = $row->getSourceIdValues()) {
        // Wipe old messages, and save any new messages.
270
        $id_map->delete($this->sourceIdValues, TRUE);
271 272 273 274
        $this->saveQueuedMessages();
      }

      try {
275 276
        $this->processRow($row);
        $save = TRUE;
277
      }
278 279 280
      catch (MigrateSkipRowException $e) {
        $id_map->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_IGNORED, $this->rollbackAction);
        $save = FALSE;
281
      }
282 283 284

      if ($save) {
        try {
285
          $destination_id_values = $destination->import($row, $id_map->lookupDestinationId($this->sourceIdValues));
286
          if ($destination_id_values) {
287 288 289 290
            // 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);
            }
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            $this->successesSinceFeedback++;
            $this->totalSuccesses++;
          }
          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());
306
          $this->message->display($e->getMessage(), 'error');
307 308 309 310 311
        }
        catch (\Exception $e) {
          $this->migration->getIdMap()->saveIdMapping($row, array(), MigrateIdMapInterface::STATUS_FAILED, $this->rollbackAction);
          $this->handleException($e);
        }
312
      }
313 314
      $this->totalProcessed++;
      $this->processedSinceFeedback++;
315 316
      if ($high_water_property = $this->migration->get('highWaterProperty')) {
        $this->migration->saveHighWater($row->getSourceProperty($high_water_property['name']));
317 318 319 320
      }

      // Reset row properties.
      unset($sourceValues, $destinationValues);
321
      $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
322 323 324 325 326 327 328 329 330 331 332 333 334

      if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
        break;
      }
      if ($this->timeOptionExceeded()) {
        break;
      }
      try {
        $source->next();
      }
      catch (\Exception $e) {
        $this->message->display(
          $this->t('Migration failed with source plugin exception: !e',
335
            array('!e' => $e->getMessage())), 'error');
336 337 338 339 340 341 342 343 344
        return MigrationInterface::RESULT_FAILED;
      }
    }

    /**
     * @TODO uncomment this
     */
    #$this->progressMessage($return);

345
    $this->migration->setMigrationResult($return);
346 347 348 349
    return $return;
  }

  /**
350
   * {@inheritdoc}
351 352 353
   */
  public function processRow(Row $row, array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
354
      $multiple = FALSE;
355
      /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
356
      foreach ($plugins as $plugin) {
357 358 359 360 361 362 363 364 365 366
        $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));
          }
367
          $break = FALSE;
368
          foreach ($value as $scalar_value) {
369 370 371 372 373 374
            try {
              $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
            }
            catch (MigrateSkipProcessException $e) {
              $break = TRUE;
            }
375 376
          }
          $value = $new_value;
377 378 379
          if ($break) {
            break;
          }
380 381
        }
        else {
382 383 384 385 386 387
          try {
            $value = $plugin->transform($value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
            break;
          }
388 389
          $multiple = $multiple || $plugin->multiple();
        }
390
      }
391 392 393 394
      // No plugins means do not set.
      if ($plugins) {
        $row->setDestinationProperty($destination, $value);
      }
395 396 397 398 399 400
      // Reset the value.
      $value = NULL;
    }
  }

  /**
401
   * Fetches the key array for the current source record.
402 403
   *
   * @return array
404
   *   The current source IDs.
405 406 407 408 409 410
   */
  protected function currentSourceIds() {
    return $this->getSource()->getCurrentIds();
  }

  /**
411
   * Tests whether we've exceeded the designated time limit.
412
   *
413 414
   * @return bool
   *   TRUE if the threshold is exceeded, FALSE if not.
415 416
   */
  protected function timeOptionExceeded() {
417
    // If there is no time limit, then it is not exceeded.
418 419 420
    if (!$time_limit = $this->getTimeLimit()) {
      return FALSE;
    }
421 422
    // Calculate if the time limit is exceeded.
    $time_elapsed = $this->getTimeElapsed();
423 424 425 426 427 428 429 430
    if ($time_elapsed >= $time_limit) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

431
  /**
432
   * {@inheritdoc}
433
   */
434
  public function getTimeLimit() {
435
    $limit = $this->limit;
436 437
    if (isset($limit['unit']) && isset($limit['value']) && ($limit['unit'] == 'seconds' || $limit['unit'] == 'second')) {
      return $limit['value'];
438 439 440 441 442 443 444
    }
    else {
      return NULL;
    }
  }

  /**
445
   * {@inheritdoc}
446 447 448 449 450 451
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->migration->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  }

  /**
452
   * {@inheritdoc}
453 454 455 456 457 458
   */
  public function queueMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->queuedMessages[] = array('message' => $message, 'level' => $level);
  }

  /**
459
   * {@inheritdoc}
460 461 462 463 464 465 466 467 468
   */
  public function saveQueuedMessages() {
    foreach ($this->queuedMessages as $queued_message) {
      $this->saveMessage($queued_message['message'], $queued_message['level']);
    }
    $this->queuedMessages = array();
  }

  /**
469 470 471
   * Checks for exceptional conditions, and display feedback.
   *
   * Standard top-of-loop stuff, common between rollback and import.
472 473 474 475 476
   */
  protected function checkStatus() {
    if ($this->memoryExceeded()) {
      return MigrationInterface::RESULT_INCOMPLETE;
    }
477
    if ($this->maxExecTimeExceeded()) {
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
      return MigrationInterface::RESULT_INCOMPLETE;
    }
    /*
     * @TODO uncomment this
    if ($this->getStatus() == MigrationInterface::STATUS_STOPPING) {
      return MigrationBase::RESULT_STOPPED;
    }
    */
    // If feedback is requested, produce a progress message at the proper time
    /*
     * @TODO uncomment this
    if (isset($this->feedback)) {
      if (($this->feedback_unit == 'seconds' && time() - $this->lastfeedback >= $this->feedback) ||
          ($this->feedback_unit == 'items' && $this->processed_since_feedback >= $this->feedback)) {
        $this->progressMessage(MigrationInterface::RESULT_INCOMPLETE);
      }
    }
    */

    return MigrationInterface::RESULT_COMPLETED;
  }

  /**
501 502 503
   * Tests whether we've exceeded the desired memory threshold.
   *
   * If so, output a message.
504
   *
505 506
   * @return bool
   *   TRUE if the threshold is exceeded, otherwise FALSE.
507 508
   */
  protected function memoryExceeded() {
509
    $usage = $this->getMemoryUsage();
510
    $pct_memory = $usage / $this->memoryLimit;
511
    if (!$threshold = $this->memoryThreshold) {
512 513 514
      return FALSE;
    }
    if ($pct_memory > $threshold) {
515
      $this->message->display(
516
        $this->t('Memory usage is !usage (!pct% of limit !limit), reclaiming memory.',
517
          array('!pct' => round($pct_memory*100),
518 519
                '!usage' => $this->formatSize($usage),
                '!limit' => $this->formatSize($this->memoryLimit))),
520
        'warning');
521 522
      $usage = $this->attemptMemoryReclaim();
      $pct_memory = $usage / $this->memoryLimit;
523 524
      // Use a lower threshold - we don't want to be in a situation where we keep
      // coming back here and trimming a tiny amount
525
      if ($pct_memory > (0.90 * $threshold)) {
526 527 528
        $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),
529 530
                  '!usage' => $this->formatSize($usage),
                  '!limit' => $this->formatSize($this->memoryLimit))),
531 532 533 534 535 536 537
          '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),
538 539
                  '!usage' => $this->formatSize($usage),
                  '!limit' => $this->formatSize($this->memoryLimit))),
540 541 542 543 544 545 546 547 548 549
          'warning');
        return FALSE;
      }
    }
    else {
      return FALSE;
    }
  }

  /**
550
   * Returns the memory usage so far.
551
   *
552 553
   * @return int
   *   The memory usage.
554
   */
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
  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();
571 572 573
  }

  /**
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
   * 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);
  }

  /**
   * Tests whether we're approaching the PHP maximum execution time limit.
   *
   * @return bool
   *   TRUE if the threshold is exceeded, FALSE if not.
   */
  protected function maxExecTimeExceeded() {
593
    return $this->maxExecTime && (($this->getTimeElapsed() / $this->maxExecTime) > $this->timeThreshold);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
  }

  /**
   * Returns the time elapsed.
   *
   * This allows a test to set a fake elapsed time.
   */
  protected function getTimeElapsed() {
    return time() - REQUEST_TIME;
  }

  /**
   * Takes an Exception object and both saves and displays it.
   *
   * Pulls in additional information on the location triggering the exception.
609 610
   *
   * @param \Exception $exception
611 612 613 614
   *   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.
615
   */
616
  protected function handleException(\Exception $exception, $save = TRUE) {
617
    $result = Error::decodeException($exception);
618 619 620 621
    $message = $result['!message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
    if ($save) {
      $this->saveMessage($message);
    }
622
    $this->message->display($message, 'error');
623 624 625
  }

}