MigrateExecutable.php 17.2 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
  protected $destinationValues;

  /**
   * The source.
   *
165
   * @var \Drupal\migrate\Plugin\MigrateSourceInterface
166 167 168 169 170 171 172 173 174
   */
  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\Plugin\MigrateSourceInterface
223
   *   The source.
224
   */
225
  protected function getSource() {
226
    if (!isset($this->source)) {
227 228 229
      $this->source = $this->migration->getSourcePlugin();

      // @TODO, find out how to remove this.
230
      // @see https://www.drupal.org/node/2443617
231
      $this->source->migrateExecutable = $this;
232 233 234 235 236
    }
    return $this->source;
  }

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

254 255 256 257 258 259 260 261 262
    $return = MigrationInterface::RESULT_COMPLETED;
    $source = $this->getSource();
    $id_map = $this->migration->getIdMap();

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

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

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

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

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

      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',
337
            array('!e' => $e->getMessage())), 'error');
338 339 340 341 342 343 344 345 346
        return MigrationInterface::RESULT_FAILED;
      }
    }

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

347
    $this->migration->setMigrationResult($return);
348 349 350 351
    return $return;
  }

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

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

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

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

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

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

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

  /**
471 472 473
   * Checks for exceptional conditions, and display feedback.
   *
   * Standard top-of-loop stuff, common between rollback and import.
474 475 476 477 478
   */
  protected function checkStatus() {
    if ($this->memoryExceeded()) {
      return MigrationInterface::RESULT_INCOMPLETE;
    }
479
    if ($this->maxExecTimeExceeded()) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
      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;
  }

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

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

  /**
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
   * 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() {
595
    return $this->maxExecTime && (($this->getTimeElapsed() / $this->maxExecTime) > $this->timeThreshold);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
  }

  /**
   * 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.
611 612
   *
   * @param \Exception $exception
613 614 615 616
   *   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.
617
   */
618
  protected function handleException(\Exception $exception, $save = TRUE) {
619
    $result = Error::decodeException($exception);
620 621 622 623
    $message = $result['!message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
    if ($save) {
      $this->saveMessage($message);
    }
624
    $this->message->display($message, 'error');
625 626 627
  }

}