MigrateExecutable.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. namespace Drupal\migrate;
  3. use Drupal\Component\Utility\Bytes;
  4. use Drupal\Core\Utility\Error;
  5. use Drupal\Core\StringTranslation\StringTranslationTrait;
  6. use Drupal\migrate\Event\MigrateEvents;
  7. use Drupal\migrate\Event\MigrateImportEvent;
  8. use Drupal\migrate\Event\MigratePostRowSaveEvent;
  9. use Drupal\migrate\Event\MigratePreRowSaveEvent;
  10. use Drupal\migrate\Event\MigrateRollbackEvent;
  11. use Drupal\migrate\Event\MigrateRowDeleteEvent;
  12. use Drupal\migrate\Exception\RequirementsException;
  13. use Drupal\migrate\Plugin\MigrateIdMapInterface;
  14. use Drupal\migrate\Plugin\MigrationInterface;
  15. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  16. /**
  17. * Defines a migrate executable class.
  18. */
  19. class MigrateExecutable implements MigrateExecutableInterface {
  20. use StringTranslationTrait;
  21. /**
  22. * The configuration of the migration to do.
  23. *
  24. * @var \Drupal\migrate\Plugin\MigrationInterface
  25. */
  26. protected $migration;
  27. /**
  28. * Status of one row.
  29. *
  30. * The value is a MigrateIdMapInterface::STATUS_* constant, for example:
  31. * STATUS_IMPORTED.
  32. *
  33. * @var int
  34. */
  35. protected $sourceRowStatus;
  36. /**
  37. * The ratio of the memory limit at which an operation will be interrupted.
  38. *
  39. * @var float
  40. */
  41. protected $memoryThreshold = 0.85;
  42. /**
  43. * The PHP memory_limit expressed in bytes.
  44. *
  45. * @var int
  46. */
  47. protected $memoryLimit;
  48. /**
  49. * The configuration values of the source.
  50. *
  51. * @var array
  52. */
  53. protected $sourceIdValues;
  54. /**
  55. * An array of counts. Initially used for cache hit/miss tracking.
  56. *
  57. * @var array
  58. */
  59. protected $counts = [];
  60. /**
  61. * The source.
  62. *
  63. * @var \Drupal\migrate\Plugin\MigrateSourceInterface
  64. */
  65. protected $source;
  66. /**
  67. * The event dispatcher.
  68. *
  69. * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
  70. */
  71. protected $eventDispatcher;
  72. /**
  73. * Migration message service.
  74. *
  75. * @todo https://www.drupal.org/node/2822663 Make this protected.
  76. *
  77. * @var \Drupal\migrate\MigrateMessageInterface
  78. */
  79. public $message;
  80. /**
  81. * Constructs a MigrateExecutable and verifies and sets the memory limit.
  82. *
  83. * @param \Drupal\migrate\Plugin\MigrationInterface $migration
  84. * The migration to run.
  85. * @param \Drupal\migrate\MigrateMessageInterface $message
  86. * (optional) The migrate message service.
  87. * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
  88. * (optional) The event dispatcher.
  89. *
  90. * @throws \Drupal\migrate\MigrateException
  91. */
  92. public function __construct(MigrationInterface $migration, MigrateMessageInterface $message = NULL, EventDispatcherInterface $event_dispatcher = NULL) {
  93. $this->migration = $migration;
  94. $this->message = $message ?: new MigrateMessage();
  95. $this->getIdMap()->setMessage($this->message);
  96. $this->eventDispatcher = $event_dispatcher;
  97. // Record the memory limit in bytes
  98. $limit = trim(ini_get('memory_limit'));
  99. if ($limit == '-1') {
  100. $this->memoryLimit = PHP_INT_MAX;
  101. }
  102. else {
  103. $this->memoryLimit = Bytes::toInt($limit);
  104. }
  105. }
  106. /**
  107. * Returns the source.
  108. *
  109. * Makes sure source is initialized based on migration settings.
  110. *
  111. * @return \Drupal\migrate\Plugin\MigrateSourceInterface
  112. * The source.
  113. */
  114. protected function getSource() {
  115. if (!isset($this->source)) {
  116. $this->source = $this->migration->getSourcePlugin();
  117. }
  118. return $this->source;
  119. }
  120. /**
  121. * Gets the event dispatcher.
  122. *
  123. * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
  124. */
  125. protected function getEventDispatcher() {
  126. if (!$this->eventDispatcher) {
  127. $this->eventDispatcher = \Drupal::service('event_dispatcher');
  128. }
  129. return $this->eventDispatcher;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. public function import() {
  135. // Only begin the import operation if the migration is currently idle.
  136. if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
  137. $this->message->display($this->t('Migration @id is busy with another operation: @status',
  138. [
  139. '@id' => $this->migration->id(),
  140. '@status' => $this->t($this->migration->getStatusLabel()),
  141. ]), 'error');
  142. return MigrationInterface::RESULT_FAILED;
  143. }
  144. $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_IMPORT, new MigrateImportEvent($this->migration, $this->message));
  145. // Knock off migration if the requirements haven't been met.
  146. try {
  147. $this->migration->checkRequirements();
  148. }
  149. catch (RequirementsException $e) {
  150. $this->message->display(
  151. $this->t(
  152. 'Migration @id did not meet the requirements. @message @requirements',
  153. [
  154. '@id' => $this->migration->id(),
  155. '@message' => $e->getMessage(),
  156. '@requirements' => $e->getRequirementsString(),
  157. ]
  158. ),
  159. 'error'
  160. );
  161. return MigrationInterface::RESULT_FAILED;
  162. }
  163. $this->migration->setStatus(MigrationInterface::STATUS_IMPORTING);
  164. $return = MigrationInterface::RESULT_COMPLETED;
  165. $source = $this->getSource();
  166. $id_map = $this->getIdMap();
  167. try {
  168. $source->rewind();
  169. }
  170. catch (\Exception $e) {
  171. $this->message->display(
  172. $this->t('Migration failed with source plugin exception: @e in @file line @line', [
  173. '@e' => $e->getMessage(),
  174. '@file' => $e->getFile(),
  175. '@line' => $e->getLine(),
  176. ]), 'error');
  177. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  178. return MigrationInterface::RESULT_FAILED;
  179. }
  180. $destination = $this->migration->getDestinationPlugin();
  181. while ($source->valid()) {
  182. $row = $source->current();
  183. $this->sourceIdValues = $row->getSourceIdValues();
  184. try {
  185. $this->processRow($row);
  186. $save = TRUE;
  187. }
  188. catch (MigrateException $e) {
  189. $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
  190. $this->saveMessage($e->getMessage(), $e->getLevel());
  191. $save = FALSE;
  192. }
  193. catch (MigrateSkipRowException $e) {
  194. if ($e->getSaveToMap()) {
  195. $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_IGNORED);
  196. }
  197. if ($message = trim($e->getMessage())) {
  198. $this->saveMessage($message, MigrationInterface::MESSAGE_INFORMATIONAL);
  199. }
  200. $save = FALSE;
  201. }
  202. if ($save) {
  203. try {
  204. $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROW_SAVE, new MigratePreRowSaveEvent($this->migration, $this->message, $row));
  205. $destination_ids = $id_map->lookupDestinationIds($this->sourceIdValues);
  206. $destination_id_values = $destination_ids ? reset($destination_ids) : [];
  207. $destination_id_values = $destination->import($row, $destination_id_values);
  208. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROW_SAVE, new MigratePostRowSaveEvent($this->migration, $this->message, $row, $destination_id_values));
  209. if ($destination_id_values) {
  210. // We do not save an idMap entry for config.
  211. if ($destination_id_values !== TRUE) {
  212. $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $destination->rollbackAction());
  213. }
  214. }
  215. else {
  216. $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
  217. if (!$id_map->messageCount()) {
  218. $message = $this->t('New object was not saved, no error provided');
  219. $this->saveMessage($message);
  220. $this->message->display($message);
  221. }
  222. }
  223. }
  224. catch (MigrateException $e) {
  225. $this->getIdMap()->saveIdMapping($row, [], $e->getStatus());
  226. $this->saveMessage($e->getMessage(), $e->getLevel());
  227. }
  228. catch (\Exception $e) {
  229. $this->getIdMap()->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
  230. $this->handleException($e);
  231. }
  232. }
  233. $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
  234. // Check for memory exhaustion.
  235. if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
  236. break;
  237. }
  238. // If anyone has requested we stop, return the requested result.
  239. if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
  240. $return = $this->migration->getInterruptionResult();
  241. $this->migration->clearInterruptionResult();
  242. break;
  243. }
  244. try {
  245. $source->next();
  246. }
  247. catch (\Exception $e) {
  248. $this->message->display(
  249. $this->t('Migration failed with source plugin exception: @e in @file line @line', [
  250. '@e' => $e->getMessage(),
  251. '@file' => $e->getFile(),
  252. '@line' => $e->getLine(),
  253. ]), 'error');
  254. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  255. return MigrationInterface::RESULT_FAILED;
  256. }
  257. }
  258. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_IMPORT, new MigrateImportEvent($this->migration, $this->message));
  259. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  260. return $return;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function rollback() {
  266. // Only begin the rollback operation if the migration is currently idle.
  267. if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
  268. $this->message->display($this->t('Migration @id is busy with another operation: @status', ['@id' => $this->migration->id(), '@status' => $this->t($this->migration->getStatusLabel())]), 'error');
  269. return MigrationInterface::RESULT_FAILED;
  270. }
  271. // Announce that rollback is about to happen.
  272. $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROLLBACK, new MigrateRollbackEvent($this->migration));
  273. // Optimistically assume things are going to work out; if not, $return will be
  274. // updated to some other status.
  275. $return = MigrationInterface::RESULT_COMPLETED;
  276. $this->migration->setStatus(MigrationInterface::STATUS_ROLLING_BACK);
  277. $id_map = $this->getIdMap();
  278. $destination = $this->migration->getDestinationPlugin();
  279. // Loop through each row in the map, and try to roll it back.
  280. $id_map->rewind();
  281. while ($id_map->valid()) {
  282. $destination_key = $id_map->currentDestination();
  283. if ($destination_key) {
  284. $map_row = $id_map->getRowByDestination($destination_key);
  285. if ($map_row['rollback_action'] == MigrateIdMapInterface::ROLLBACK_DELETE) {
  286. $this->getEventDispatcher()
  287. ->dispatch(MigrateEvents::PRE_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
  288. $destination->rollback($destination_key);
  289. $this->getEventDispatcher()
  290. ->dispatch(MigrateEvents::POST_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
  291. }
  292. // We're now done with this row, so remove it from the map.
  293. $id_map->deleteDestination($destination_key);
  294. }
  295. else {
  296. // If there is no destination key the import probably failed and we can
  297. // remove the row without further action.
  298. $source_key = $id_map->currentSource();
  299. $id_map->delete($source_key);
  300. }
  301. $id_map->next();
  302. // Check for memory exhaustion.
  303. if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
  304. break;
  305. }
  306. // If anyone has requested we stop, return the requested result.
  307. if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
  308. $return = $this->migration->getInterruptionResult();
  309. $this->migration->clearInterruptionResult();
  310. break;
  311. }
  312. }
  313. // Notify modules that rollback attempt was complete.
  314. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROLLBACK, new MigrateRollbackEvent($this->migration));
  315. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  316. return $return;
  317. }
  318. /**
  319. * Get the ID map from the current migration.
  320. *
  321. * @return \Drupal\migrate\Plugin\MigrateIdMapInterface
  322. * The ID map.
  323. */
  324. protected function getIdMap() {
  325. return $this->migration->getIdMap();
  326. }
  327. /**
  328. * {@inheritdoc}
  329. */
  330. public function processRow(Row $row, array $process = NULL, $value = NULL) {
  331. foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
  332. $multiple = FALSE;
  333. /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
  334. foreach ($plugins as $plugin) {
  335. $definition = $plugin->getPluginDefinition();
  336. // Many plugins expect a scalar value but the current value of the
  337. // pipeline might be multiple scalars (this is set by the previous
  338. // plugin) and in this case the current value needs to be iterated
  339. // and each scalar separately transformed.
  340. if ($multiple && !$definition['handle_multiples']) {
  341. $new_value = [];
  342. if (!is_array($value)) {
  343. throw new MigrateException(sprintf('Pipeline failed at %s plugin for destination %s: %s received instead of an array,', $plugin->getPluginId(), $destination, $value));
  344. }
  345. $break = FALSE;
  346. foreach ($value as $scalar_value) {
  347. try {
  348. $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
  349. }
  350. catch (MigrateSkipProcessException $e) {
  351. $new_value[] = NULL;
  352. $break = TRUE;
  353. }
  354. }
  355. $value = $new_value;
  356. if ($break) {
  357. break;
  358. }
  359. }
  360. else {
  361. try {
  362. $value = $plugin->transform($value, $this, $row, $destination);
  363. }
  364. catch (MigrateSkipProcessException $e) {
  365. $value = NULL;
  366. break;
  367. }
  368. $multiple = $plugin->multiple();
  369. }
  370. }
  371. // Ensure all values, including nulls, are migrated.
  372. if ($plugins) {
  373. if (isset($value)) {
  374. $row->setDestinationProperty($destination, $value);
  375. }
  376. else {
  377. $row->setEmptyDestinationProperty($destination);
  378. }
  379. }
  380. // Reset the value.
  381. $value = NULL;
  382. }
  383. }
  384. /**
  385. * Fetches the key array for the current source record.
  386. *
  387. * @return array
  388. * The current source IDs.
  389. */
  390. protected function currentSourceIds() {
  391. return $this->getSource()->getCurrentIds();
  392. }
  393. /**
  394. * {@inheritdoc}
  395. */
  396. public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
  397. $this->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  398. }
  399. /**
  400. * Takes an Exception object and both saves and displays it.
  401. *
  402. * Pulls in additional information on the location triggering the exception.
  403. *
  404. * @param \Exception $exception
  405. * Object representing the exception.
  406. * @param bool $save
  407. * (optional) Whether to save the message in the migration's mapping table.
  408. * Set to FALSE in contexts where this doesn't make sense.
  409. */
  410. protected function handleException(\Exception $exception, $save = TRUE) {
  411. $result = Error::decodeException($exception);
  412. $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
  413. if ($save) {
  414. $this->saveMessage($message);
  415. }
  416. $this->message->display($message, 'error');
  417. }
  418. /**
  419. * Checks for exceptional conditions, and display feedback.
  420. */
  421. protected function checkStatus() {
  422. if ($this->memoryExceeded()) {
  423. return MigrationInterface::RESULT_INCOMPLETE;
  424. }
  425. return MigrationInterface::RESULT_COMPLETED;
  426. }
  427. /**
  428. * Tests whether we've exceeded the desired memory threshold.
  429. *
  430. * If so, output a message.
  431. *
  432. * @return bool
  433. * TRUE if the threshold is exceeded, otherwise FALSE.
  434. */
  435. protected function memoryExceeded() {
  436. $usage = $this->getMemoryUsage();
  437. $pct_memory = $usage / $this->memoryLimit;
  438. if (!$threshold = $this->memoryThreshold) {
  439. return FALSE;
  440. }
  441. if ($pct_memory > $threshold) {
  442. $this->message->display(
  443. $this->t(
  444. 'Memory usage is @usage (@pct% of limit @limit), reclaiming memory.',
  445. [
  446. '@pct' => round($pct_memory * 100),
  447. '@usage' => $this->formatSize($usage),
  448. '@limit' => $this->formatSize($this->memoryLimit),
  449. ]
  450. ),
  451. 'warning'
  452. );
  453. $usage = $this->attemptMemoryReclaim();
  454. $pct_memory = $usage / $this->memoryLimit;
  455. // Use a lower threshold - we don't want to be in a situation where we keep
  456. // coming back here and trimming a tiny amount
  457. if ($pct_memory > (0.90 * $threshold)) {
  458. $this->message->display(
  459. $this->t(
  460. 'Memory usage is now @usage (@pct% of limit @limit), not enough reclaimed, starting new batch',
  461. [
  462. '@pct' => round($pct_memory * 100),
  463. '@usage' => $this->formatSize($usage),
  464. '@limit' => $this->formatSize($this->memoryLimit),
  465. ]
  466. ),
  467. 'warning'
  468. );
  469. return TRUE;
  470. }
  471. else {
  472. $this->message->display(
  473. $this->t(
  474. 'Memory usage is now @usage (@pct% of limit @limit), reclaimed enough, continuing',
  475. [
  476. '@pct' => round($pct_memory * 100),
  477. '@usage' => $this->formatSize($usage),
  478. '@limit' => $this->formatSize($this->memoryLimit),
  479. ]
  480. ),
  481. 'warning');
  482. return FALSE;
  483. }
  484. }
  485. else {
  486. return FALSE;
  487. }
  488. }
  489. /**
  490. * Returns the memory usage so far.
  491. *
  492. * @return int
  493. * The memory usage.
  494. */
  495. protected function getMemoryUsage() {
  496. return memory_get_usage();
  497. }
  498. /**
  499. * Tries to reclaim memory.
  500. *
  501. * @return int
  502. * The memory usage after reclaim.
  503. */
  504. protected function attemptMemoryReclaim() {
  505. // First, try resetting Drupal's static storage - this frequently releases
  506. // plenty of memory to continue.
  507. drupal_static_reset();
  508. // Entity storage can blow up with caches so clear them out.
  509. $entity_type_manager = \Drupal::entityTypeManager();
  510. foreach ($entity_type_manager->getDefinitions() as $id => $definition) {
  511. $entity_type_manager->getStorage($id)->resetCache();
  512. }
  513. // @TODO: explore resetting the container.
  514. // Run garbage collector to further reduce memory.
  515. gc_collect_cycles();
  516. return memory_get_usage();
  517. }
  518. /**
  519. * Generates a string representation for the given byte count.
  520. *
  521. * @param int $size
  522. * A size in bytes.
  523. *
  524. * @return string
  525. * A translated string representation of the size.
  526. */
  527. protected function formatSize($size) {
  528. return format_size($size);
  529. }
  530. }