MigrateExecutable.php 18.3 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 19
use Drupal\migrate\Plugin\MigrateIdMapInterface;

/**
 * Defines a migrate executable class.
 */
class MigrateExecutable {
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 226 227 228 229 230 231 232
   */
  public function getSource() {
    if (!isset($this->source)) {
      $this->source = new Source($this->migration, $this);
    }
    return $this->source;
  }

  /**
233
   * Performs an import operation - migrate items from source to destination.
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 351 352
   * Processes a row.
   *
   * @param \Drupal\migrate\Row $row
353 354
   *   The $row to be processed.
   * @param array $process
355 356
   *   (optional) A process pipeline configuration. If not set, the top level
   *   process configuration in the migration entity is used.
357
   * @param mixed $value
358
   *   (optional) Initial value of the pipeline for the first destination.
359 360 361 362 363
   *   Usually setting this is not necessary as $process typically starts with
   *   a 'get'. This is useful only when the $process contains a single
   *   destination and needs to access a value outside of the source. See
   *   \Drupal\migrate\Plugin\migrate\process\Iterator::transformKey for an
   *   example.
364 365
   *
   * @throws \Drupal\migrate\MigrateException
366 367 368
   */
  public function processRow(Row $row, array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
369
      $multiple = FALSE;
370
      /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
371
      foreach ($plugins as $plugin) {
372 373 374 375 376 377 378 379 380 381
        $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));
          }
382
          $break = FALSE;
383
          foreach ($value as $scalar_value) {
384 385 386 387 388 389
            try {
              $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
            }
            catch (MigrateSkipProcessException $e) {
              $break = TRUE;
            }
390 391
          }
          $value = $new_value;
392 393 394
          if ($break) {
            break;
          }
395 396
        }
        else {
397 398 399 400 401 402
          try {
            $value = $plugin->transform($value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
            break;
          }
403 404
          $multiple = $multiple || $plugin->multiple();
        }
405
      }
406 407 408 409
      // No plugins means do not set.
      if ($plugins) {
        $row->setDestinationProperty($destination, $value);
      }
410 411 412 413 414 415
      // Reset the value.
      $value = NULL;
    }
  }

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

  /**
426
   * Tests whether we've exceeded the designated time limit.
427
   *
428 429
   * @return bool
   *   TRUE if the threshold is exceeded, FALSE if not.
430 431
   */
  protected function timeOptionExceeded() {
432
    // If there is no time limit, then it is not exceeded.
433 434 435
    if (!$time_limit = $this->getTimeLimit()) {
      return FALSE;
    }
436 437
    // Calculate if the time limit is exceeded.
    $time_elapsed = $this->getTimeElapsed();
438 439 440 441 442 443 444 445
    if ($time_elapsed >= $time_limit) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

446 447 448 449 450 451
  /**
   * Returns the time limit.
   *
   * @return null|int
   *   The time limit, NULL if no limit or if the units were not in seconds.
   */
452
  public function getTimeLimit() {
453
    $limit = $this->limit;
454 455
    if (isset($limit['unit']) && isset($limit['value']) && ($limit['unit'] == 'seconds' || $limit['unit'] == 'second')) {
      return $limit['value'];
456 457 458 459 460 461 462
    }
    else {
      return NULL;
    }
  }

  /**
463
   * Passes messages through to the map class.
464 465
   *
   * @param string $message
466
   *   The message to record.
467
   * @param int $level
468
   *   (optional) Message severity (defaults to MESSAGE_ERROR).
469 470 471 472 473 474
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->migration->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  }

  /**
475
   * Queues messages to be later saved through the map class.
476 477
   *
   * @param string $message
478
   *   The message to record.
479
   * @param int $level
480
   *   (optional) Message severity (defaults to MESSAGE_ERROR).
481 482 483 484 485 486
   */
  public function queueMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->queuedMessages[] = array('message' => $message, 'level' => $level);
  }

  /**
487
   * Saves any messages we've queued up to the message table.
488 489 490 491 492 493 494 495 496
   */
  public function saveQueuedMessages() {
    foreach ($this->queuedMessages as $queued_message) {
      $this->saveMessage($queued_message['message'], $queued_message['level']);
    }
    $this->queuedMessages = array();
  }

  /**
497 498 499
   * Checks for exceptional conditions, and display feedback.
   *
   * Standard top-of-loop stuff, common between rollback and import.
500 501 502 503 504
   */
  protected function checkStatus() {
    if ($this->memoryExceeded()) {
      return MigrationInterface::RESULT_INCOMPLETE;
    }
505
    if ($this->maxExecTimeExceeded()) {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
      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;
  }

  /**
529 530 531
   * Tests whether we've exceeded the desired memory threshold.
   *
   * If so, output a message.
532
   *
533 534
   * @return bool
   *   TRUE if the threshold is exceeded, otherwise FALSE.
535 536
   */
  protected function memoryExceeded() {
537
    $usage = $this->getMemoryUsage();
538
    $pct_memory = $usage / $this->memoryLimit;
539
    if (!$threshold = $this->memoryThreshold) {
540 541 542
      return FALSE;
    }
    if ($pct_memory > $threshold) {
543
      $this->message->display(
544
        $this->t('Memory usage is !usage (!pct% of limit !limit), reclaiming memory.',
545
          array('!pct' => round($pct_memory*100),
546 547
                '!usage' => $this->formatSize($usage),
                '!limit' => $this->formatSize($this->memoryLimit))),
548
        'warning');
549 550
      $usage = $this->attemptMemoryReclaim();
      $pct_memory = $usage / $this->memoryLimit;
551 552
      // Use a lower threshold - we don't want to be in a situation where we keep
      // coming back here and trimming a tiny amount
553
      if ($pct_memory > (0.90 * $threshold)) {
554 555 556
        $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),
557 558
                  '!usage' => $this->formatSize($usage),
                  '!limit' => $this->formatSize($this->memoryLimit))),
559 560 561 562 563 564 565
          '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),
566 567
                  '!usage' => $this->formatSize($usage),
                  '!limit' => $this->formatSize($this->memoryLimit))),
568 569 570 571 572 573 574 575 576 577
          'warning');
        return FALSE;
      }
    }
    else {
      return FALSE;
    }
  }

  /**
578
   * Returns the memory usage so far.
579
   *
580 581
   * @return int
   *   The memory usage.
582
   */
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
  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();
599 600 601
  }

  /**
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
   * 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() {
621
    return $this->maxExecTime && (($this->getTimeElapsed() / $this->maxExecTime) > $this->timeThreshold);
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
  }

  /**
   * 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.
637 638
   *
   * @param \Exception $exception
639 640 641 642
   *   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.
643
   */
644
  public function handleException(\Exception $exception, $save = TRUE) {
645
    $result = Error::decodeException($exception);
646 647 648 649
    $message = $result['!message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
    if ($save) {
      $this->saveMessage($message);
    }
650
    $this->message->display($message, 'error');
651 652 653
  }

}