summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/migrate/src/MigrateExecutable.php
blob: a087ae6875e4902abf451db4313ca5f5e48aa276 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<?php

namespace Drupal\migrate;

use Drupal\Component\Utility\Bytes;
use Drupal\Core\StringTranslation\ByteSizeMarkup;
use Drupal\Core\Utility\Error;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\migrate\Event\MigratePostRowSaveEvent;
use Drupal\migrate\Event\MigratePreRowSaveEvent;
use Drupal\migrate\Event\MigrateRollbackEvent;
use Drupal\migrate\Event\MigrateRowDeleteEvent;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * Defines a migrate executable class.
 */
class MigrateExecutable implements MigrateExecutableInterface {
  use StringTranslationTrait;

  /**
   * The configuration of the migration to do.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

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

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

  /**
   * The configuration values of the source.
   *
   * @var array
   */
  protected $sourceIdValues;

  /**
   * An array of counts. Initially used for cache hit/miss tracking.
   *
   * @var array
   */
  protected $counts = [];

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

  /**
   * The event dispatcher.
   *
   * @var \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * Migration message service.
   *
   * @var \Drupal\migrate\MigrateMessageInterface
   *
   * @todo https://www.drupal.org/node/2822663 Make this protected.
   */
  public $message;

  /**
   * Constructs a MigrateExecutable and verifies and sets the memory limit.
   *
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The migration to run.
   * @param \Drupal\migrate\MigrateMessageInterface $message
   *   (optional) The migrate message service.
   * @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   (optional) The event dispatcher.
   */
  public function __construct(MigrationInterface $migration, ?MigrateMessageInterface $message = NULL, ?EventDispatcherInterface $event_dispatcher = NULL) {
    $this->migration = $migration;
    $this->message = $message ?: new MigrateMessage();
    $this->getIdMap()->setMessage($this->message);
    $this->eventDispatcher = $event_dispatcher;
    // Record the memory limit in bytes
    $limit = trim(ini_get('memory_limit'));
    if ($limit == '-1') {
      $this->memoryLimit = PHP_INT_MAX;
    }
    else {
      $this->memoryLimit = Bytes::toNumber($limit);
    }
  }

  /**
   * Returns the source.
   *
   * Makes sure source is initialized based on migration settings.
   *
   * @return \Drupal\migrate\Plugin\MigrateSourceInterface
   *   The source.
   */
  protected function getSource() {
    if (!isset($this->source)) {
      $this->source = $this->migration->getSourcePlugin();
    }
    return $this->source;
  }

  /**
   * Gets the event dispatcher.
   *
   * @return \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
   *   The event dispatcher service.
   */
  protected function getEventDispatcher() {
    if (!$this->eventDispatcher) {
      $this->eventDispatcher = \Drupal::service('event_dispatcher');
    }
    return $this->eventDispatcher;
  }

  /**
   * {@inheritdoc}
   */
  public function import() {
    // 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',
        [
          '@id' => $this->migration->id(),
          // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
          '@status' => $this->t($this->migration->getStatusLabel()),
        ]), 'error');
      return MigrationInterface::RESULT_FAILED;
    }
    $this->getEventDispatcher()->dispatch(new MigrateImportEvent($this->migration, $this->message), MigrateEvents::PRE_IMPORT);

    // Knock off migration if the requirements haven't been met.
    try {
      $this->migration->checkRequirements();
    }
    catch (RequirementsException $e) {
      $this->message->display(
        $this->t(
          'Migration @id did not meet the requirements. @message',
          [
            '@id' => $this->migration->id(),
            '@message' => $e->getMessage(),
          ]
        ),
        'error'
      );

      return MigrationInterface::RESULT_FAILED;
    }

    $this->migration->setStatus(MigrationInterface::STATUS_IMPORTING);
    $source = $this->getSource();

    try {
      $source->rewind();
    }
    catch (\Exception $e) {
      $this->message->display(
        $this->t('Migration failed with source plugin exception: @e in @file line @line', [
          '@e' => $e->getMessage(),
          '@file' => $e->getFile(),
          '@line' => $e->getLine(),
        ]), 'error');
      $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
      return MigrationInterface::RESULT_FAILED;
    }

    // Get the process pipeline.
    $pipeline = FALSE;
    if ($source->valid()) {
      try {
        $pipeline = $this->migration->getProcessPlugins();
      }
      catch (MigrateException $e) {
        $row = $source->current();
        $this->sourceIdValues = $row->getSourceIdValues();
        $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
        $this->saveMessage($e->getMessage(), $e->getLevel());
      }
    }

    $return = MigrationInterface::RESULT_COMPLETED;
    if ($pipeline) {
      $id_map = $this->getIdMap();
      $destination = $this->migration->getDestinationPlugin();
      while ($source->valid()) {
        $row = $source->current();
        $this->sourceIdValues = $row->getSourceIdValues();

        try {
          foreach ($pipeline as $destination_property_name => $plugins) {
            $this->processPipeline($row, $destination_property_name, $plugins, NULL);
          }
          $save = TRUE;
        }
        catch (MigrateException $e) {
          $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
          $msg = sprintf("%s:%s:%s", $this->migration->getPluginId(), $destination_property_name, $e->getMessage());
          $this->saveMessage($msg, $e->getLevel());
          $save = FALSE;
        }
        catch (MigrateSkipRowException $e) {
          if ($e->getSaveToMap()) {
            $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_IGNORED);
          }
          if ($message = trim($e->getMessage())) {
            $msg = sprintf("%s:%s: %s", $this->migration->getPluginId(), $destination_property_name, $message);
            $this->saveMessage($msg, MigrationInterface::MESSAGE_INFORMATIONAL);
          }
          $save = FALSE;
        }

        if ($save) {
          try {
            $this->getEventDispatcher()
              ->dispatch(new MigratePreRowSaveEvent($this->migration, $this->message, $row), MigrateEvents::PRE_ROW_SAVE);
            $destination_ids = $id_map->lookupDestinationIds($this->sourceIdValues);
            $destination_id_values = $destination_ids ? reset($destination_ids) : [];
            $destination_id_values = $destination->import($row, $destination_id_values);
            $this->getEventDispatcher()
              ->dispatch(new MigratePostRowSaveEvent($this->migration, $this->message, $row, $destination_id_values), MigrateEvents::POST_ROW_SAVE);
            if ($destination_id_values) {
              // We do not save an idMap entry for config.
              if ($destination_id_values !== TRUE) {
                $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $destination->rollbackAction());
              }
            }
            else {
              $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
              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->getIdMap()->saveIdMapping($row, [], $e->getStatus());
            $this->saveMessage($e->getMessage(), $e->getLevel());
          }
          catch (\Exception $e) {
            $this->getIdMap()
              ->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
            $this->handleException($e);
          }
        }

        $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;

        // 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) {
          $return = $this->migration->getInterruptionResult();
          $this->migration->clearInterruptionResult();
          break;
        }

        try {
          $source->next();
        }
        catch (\Exception $e) {
          $this->message->display(
            $this->t('Migration failed with source plugin exception: @e in @file line @line', [
              '@e' => $e->getMessage(),
              '@file' => $e->getFile(),
              '@line' => $e->getLine(),
            ]), 'error');
          $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
          return MigrationInterface::RESULT_FAILED;
        }
      }
    }

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

  /**
   * {@inheritdoc}
   */
  public function rollback() {
    // Only begin the rollback operation if the migration is currently idle.
    if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
      // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
      $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(new MigrateRollbackEvent($this->migration), MigrateEvents::PRE_ROLLBACK);

    // 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->getIdMap();
    $destination = $this->migration->getDestinationPlugin();

    // Loop through each row in the map, and try to roll it back.
    $id_map->rewind();
    while ($id_map->valid()) {
      $destination_key = $id_map->currentDestination();
      if ($destination_key) {
        $map_row = $id_map->getRowByDestination($destination_key);
        if (!isset($map_row['rollback_action']) || $map_row['rollback_action'] == MigrateIdMapInterface::ROLLBACK_DELETE) {
          $this->getEventDispatcher()
            ->dispatch(new MigrateRowDeleteEvent($this->migration, $destination_key), MigrateEvents::PRE_ROW_DELETE);
          $destination->rollback($destination_key);
          $this->getEventDispatcher()
            ->dispatch(new MigrateRowDeleteEvent($this->migration, $destination_key), MigrateEvents::POST_ROW_DELETE);
        }
        // We're now done with this row, so remove it from the map.
        $id_map->deleteDestination($destination_key);
      }
      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);
      }
      $id_map->next();

      // 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) {
        $return = $this->migration->getInterruptionResult();
        $this->migration->clearInterruptionResult();
        break;
      }
    }

    // Notify modules that rollback attempt was complete.
    $this->getEventDispatcher()->dispatch(new MigrateRollbackEvent($this->migration), MigrateEvents::POST_ROLLBACK);
    $this->migration->setStatus(MigrationInterface::STATUS_IDLE);

    return $return;
  }

  /**
   * Get the ID map from the current migration.
   *
   * @return \Drupal\migrate\Plugin\MigrateIdMapInterface
   *   The ID map.
   */
  protected function getIdMap() {
    return $this->migration->getIdMap();
  }

  /**
   * {@inheritdoc}
   */
  public function processRow(Row $row, ?array $process = NULL, $value = NULL) {
    foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
      $this->processPipeline($row, $destination, $plugins, $value);
    }
  }

  /**
   * Runs a process pipeline.
   *
   * @param \Drupal\migrate\Row $row
   *   The $row to be processed.
   * @param string $destination
   *   The destination property name.
   * @param array $plugins
   *   The process pipeline plugins.
   * @param mixed $value
   *   (optional) Initial value of the pipeline for the destination.
   *
   * @see \Drupal\migrate\MigrateExecutableInterface::processRow
   *
   * @throws \Drupal\migrate\MigrateException
   */
  protected function processPipeline(Row $row, string $destination, array $plugins, $value) {
    $multiple = FALSE;
    /** @var \Drupal\migrate\Plugin\MigrateProcessInterface $plugin */
    foreach ($plugins as $plugin) {
      $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 = [];
        if (!is_array($value)) {
          throw new MigrateException(sprintf('Pipeline failed at %s plugin for destination %s: %s received instead of an array,', $plugin->getPluginId(), $destination, $value));
        }
        $break = FALSE;
        foreach ($value as $scalar_value) {
          $plugin->reset();
          try {
            $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
          }
          catch (MigrateSkipProcessException $e) {
            $new_value[] = NULL;
            $break = TRUE;
          }
          catch (MigrateException $e) {
            // Prepend the process plugin id to the message.
            $message = sprintf("%s: %s", $plugin->getPluginId(), $e->getMessage());
            throw new MigrateException($message);
          }
          if ($plugin->isPipelineStopped()) {
            $break = TRUE;
          }
        }
        $value = $new_value;
        if ($break) {
          break;
        }
      }
      else {
        $plugin->reset();
        try {
          $value = $plugin->transform($value, $this, $row, $destination);
        }
        catch (MigrateSkipProcessException) {
          $value = NULL;
          break;
        }
        catch (MigrateException $e) {
          // Prepend the process plugin id to the message.
          $message = sprintf("%s: %s", $plugin->getPluginId(), $e->getMessage());
          throw new MigrateException($message);
        }
        if ($plugin->isPipelineStopped()) {
          break;
        }
        $multiple = $plugin->multiple();
      }
    }
    // Ensure all values, including nulls, are migrated.
    if ($plugins) {
      if (isset($value)) {
        $row->setDestinationProperty($destination, $value);
      }
      else {
        $row->setEmptyDestinationProperty($destination);
      }
    }
  }

  /**
   * Fetches the key array for the current source record.
   *
   * @return array
   *   The current source IDs.
   */
  protected function currentSourceIds() {
    return $this->getSource()->getCurrentIds();
  }

  /**
   * {@inheritdoc}
   */
  public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
    $this->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  }

  /**
   * Takes an Exception object and both saves and displays it.
   *
   * Pulls in additional information on the location triggering the exception.
   *
   * @param \Exception $exception
   *   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.
   */
  protected function handleException(\Exception $exception, $save = TRUE) {
    $result = Error::decodeException($exception);
    $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
    if ($save) {
      $this->saveMessage($message);
    }
    $this->message->display($message, 'error');
  }

  /**
   * 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.',
          [
            '@pct' => round($pct_memory * 100),
            '@usage' => ByteSizeMarkup::create($usage, NULL, $this->stringTranslation),
            '@limit' => ByteSizeMarkup::create($this->memoryLimit, NULL, $this->stringTranslation),
          ]
        ),
        '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',
            [
              '@pct' => round($pct_memory * 100),
              '@usage' => ByteSizeMarkup::create($usage, NULL, $this->stringTranslation),
              '@limit' => ByteSizeMarkup::create($this->memoryLimit, NULL, $this->stringTranslation),
            ]
          ),
          'warning'
        );
        return TRUE;
      }
      else {
        $this->message->display(
          $this->t(
            'Memory usage is now @usage (@pct% of limit @limit), reclaimed enough, continuing',
            [
              '@pct' => round($pct_memory * 100),
              '@usage' => ByteSizeMarkup::create($usage, NULL, $this->stringTranslation),
              '@limit' => ByteSizeMarkup::create($this->memoryLimit, NULL, $this->stringTranslation),
            ]
          ),
          '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.

    // Run garbage collector to further reduce memory.
    gc_collect_cycles();

    return memory_get_usage();
  }

}