MigrateExecutable.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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->migration->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->migration->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', ['@e' => $e->getMessage()]), 'error');
  173. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  174. return MigrationInterface::RESULT_FAILED;
  175. }
  176. $destination = $this->migration->getDestinationPlugin();
  177. while ($source->valid()) {
  178. $row = $source->current();
  179. $this->sourceIdValues = $row->getSourceIdValues();
  180. try {
  181. $this->processRow($row);
  182. $save = TRUE;
  183. }
  184. catch (MigrateException $e) {
  185. $this->migration->getIdMap()->saveIdMapping($row, [], $e->getStatus());
  186. $this->saveMessage($e->getMessage(), $e->getLevel());
  187. $save = FALSE;
  188. }
  189. catch (MigrateSkipRowException $e) {
  190. if ($e->getSaveToMap()) {
  191. $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_IGNORED);
  192. }
  193. if ($message = trim($e->getMessage())) {
  194. $this->saveMessage($message, MigrationInterface::MESSAGE_INFORMATIONAL);
  195. }
  196. $save = FALSE;
  197. }
  198. if ($save) {
  199. try {
  200. $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROW_SAVE, new MigratePreRowSaveEvent($this->migration, $this->message, $row));
  201. $destination_ids = $id_map->lookupDestinationIds($this->sourceIdValues);
  202. $destination_id_values = $destination_ids ? reset($destination_ids) : [];
  203. $destination_id_values = $destination->import($row, $destination_id_values);
  204. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROW_SAVE, new MigratePostRowSaveEvent($this->migration, $this->message, $row, $destination_id_values));
  205. if ($destination_id_values) {
  206. // We do not save an idMap entry for config.
  207. if ($destination_id_values !== TRUE) {
  208. $id_map->saveIdMapping($row, $destination_id_values, $this->sourceRowStatus, $destination->rollbackAction());
  209. }
  210. }
  211. else {
  212. $id_map->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
  213. if (!$id_map->messageCount()) {
  214. $message = $this->t('New object was not saved, no error provided');
  215. $this->saveMessage($message);
  216. $this->message->display($message);
  217. }
  218. }
  219. }
  220. catch (MigrateException $e) {
  221. $this->migration->getIdMap()->saveIdMapping($row, [], $e->getStatus());
  222. $this->saveMessage($e->getMessage(), $e->getLevel());
  223. }
  224. catch (\Exception $e) {
  225. $this->migration->getIdMap()->saveIdMapping($row, [], MigrateIdMapInterface::STATUS_FAILED);
  226. $this->handleException($e);
  227. }
  228. }
  229. $this->sourceRowStatus = MigrateIdMapInterface::STATUS_IMPORTED;
  230. // Check for memory exhaustion.
  231. if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
  232. break;
  233. }
  234. // If anyone has requested we stop, return the requested result.
  235. if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
  236. $return = $this->migration->getInterruptionResult();
  237. $this->migration->clearInterruptionResult();
  238. break;
  239. }
  240. try {
  241. $source->next();
  242. }
  243. catch (\Exception $e) {
  244. $this->message->display(
  245. $this->t('Migration failed with source plugin exception: @e',
  246. ['@e' => $e->getMessage()]), 'error');
  247. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  248. return MigrationInterface::RESULT_FAILED;
  249. }
  250. }
  251. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_IMPORT, new MigrateImportEvent($this->migration, $this->message));
  252. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  253. return $return;
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function rollback() {
  259. // Only begin the rollback operation if the migration is currently idle.
  260. if ($this->migration->getStatus() !== MigrationInterface::STATUS_IDLE) {
  261. $this->message->display($this->t('Migration @id is busy with another operation: @status', ['@id' => $this->migration->id(), '@status' => $this->t($this->migration->getStatusLabel())]), 'error');
  262. return MigrationInterface::RESULT_FAILED;
  263. }
  264. // Announce that rollback is about to happen.
  265. $this->getEventDispatcher()->dispatch(MigrateEvents::PRE_ROLLBACK, new MigrateRollbackEvent($this->migration));
  266. // Optimistically assume things are going to work out; if not, $return will be
  267. // updated to some other status.
  268. $return = MigrationInterface::RESULT_COMPLETED;
  269. $this->migration->setStatus(MigrationInterface::STATUS_ROLLING_BACK);
  270. $id_map = $this->migration->getIdMap();
  271. $destination = $this->migration->getDestinationPlugin();
  272. // Loop through each row in the map, and try to roll it back.
  273. foreach ($id_map as $map_row) {
  274. $destination_key = $id_map->currentDestination();
  275. if ($destination_key) {
  276. $map_row = $id_map->getRowByDestination($destination_key);
  277. if ($map_row['rollback_action'] == MigrateIdMapInterface::ROLLBACK_DELETE) {
  278. $this->getEventDispatcher()
  279. ->dispatch(MigrateEvents::PRE_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
  280. $destination->rollback($destination_key);
  281. $this->getEventDispatcher()
  282. ->dispatch(MigrateEvents::POST_ROW_DELETE, new MigrateRowDeleteEvent($this->migration, $destination_key));
  283. }
  284. // We're now done with this row, so remove it from the map.
  285. $id_map->deleteDestination($destination_key);
  286. }
  287. else {
  288. // If there is no destination key the import probably failed and we can
  289. // remove the row without further action.
  290. $source_key = $id_map->currentSource();
  291. $id_map->delete($source_key);
  292. }
  293. // Check for memory exhaustion.
  294. if (($return = $this->checkStatus()) != MigrationInterface::RESULT_COMPLETED) {
  295. break;
  296. }
  297. // If anyone has requested we stop, return the requested result.
  298. if ($this->migration->getStatus() == MigrationInterface::STATUS_STOPPING) {
  299. $return = $this->migration->getInterruptionResult();
  300. $this->migration->clearInterruptionResult();
  301. break;
  302. }
  303. }
  304. // Notify modules that rollback attempt was complete.
  305. $this->getEventDispatcher()->dispatch(MigrateEvents::POST_ROLLBACK, new MigrateRollbackEvent($this->migration));
  306. $this->migration->setStatus(MigrationInterface::STATUS_IDLE);
  307. return $return;
  308. }
  309. /**
  310. * {@inheritdoc}
  311. */
  312. public function processRow(Row $row, array $process = NULL, $value = NULL) {
  313. foreach ($this->migration->getProcessPlugins($process) as $destination => $plugins) {
  314. $multiple = FALSE;
  315. /** @var $plugin \Drupal\migrate\Plugin\MigrateProcessInterface */
  316. foreach ($plugins as $plugin) {
  317. $definition = $plugin->getPluginDefinition();
  318. // Many plugins expect a scalar value but the current value of the
  319. // pipeline might be multiple scalars (this is set by the previous
  320. // plugin) and in this case the current value needs to be iterated
  321. // and each scalar separately transformed.
  322. if ($multiple && !$definition['handle_multiples']) {
  323. $new_value = [];
  324. if (!is_array($value)) {
  325. throw new MigrateException(sprintf('Pipeline failed at %s plugin for destination %s: %s received instead of an array,', $plugin->getPluginId(), $destination, $value));
  326. }
  327. $break = FALSE;
  328. foreach ($value as $scalar_value) {
  329. try {
  330. $new_value[] = $plugin->transform($scalar_value, $this, $row, $destination);
  331. }
  332. catch (MigrateSkipProcessException $e) {
  333. $new_value[] = NULL;
  334. $break = TRUE;
  335. }
  336. }
  337. $value = $new_value;
  338. if ($break) {
  339. break;
  340. }
  341. }
  342. else {
  343. try {
  344. $value = $plugin->transform($value, $this, $row, $destination);
  345. }
  346. catch (MigrateSkipProcessException $e) {
  347. $value = NULL;
  348. break;
  349. }
  350. $multiple = $plugin->multiple();
  351. }
  352. }
  353. // Ensure all values, including nulls, are migrated.
  354. if ($plugins) {
  355. if (isset($value)) {
  356. $row->setDestinationProperty($destination, $value);
  357. }
  358. else {
  359. $row->setEmptyDestinationProperty($destination);
  360. }
  361. }
  362. // Reset the value.
  363. $value = NULL;
  364. }
  365. }
  366. /**
  367. * Fetches the key array for the current source record.
  368. *
  369. * @return array
  370. * The current source IDs.
  371. */
  372. protected function currentSourceIds() {
  373. return $this->getSource()->getCurrentIds();
  374. }
  375. /**
  376. * {@inheritdoc}
  377. */
  378. public function saveMessage($message, $level = MigrationInterface::MESSAGE_ERROR) {
  379. $this->migration->getIdMap()->saveMessage($this->sourceIdValues, $message, $level);
  380. }
  381. /**
  382. * Takes an Exception object and both saves and displays it.
  383. *
  384. * Pulls in additional information on the location triggering the exception.
  385. *
  386. * @param \Exception $exception
  387. * Object representing the exception.
  388. * @param bool $save
  389. * (optional) Whether to save the message in the migration's mapping table.
  390. * Set to FALSE in contexts where this doesn't make sense.
  391. */
  392. protected function handleException(\Exception $exception, $save = TRUE) {
  393. $result = Error::decodeException($exception);
  394. $message = $result['@message'] . ' (' . $result['%file'] . ':' . $result['%line'] . ')';
  395. if ($save) {
  396. $this->saveMessage($message);
  397. }
  398. $this->message->display($message, 'error');
  399. }
  400. /**
  401. * Checks for exceptional conditions, and display feedback.
  402. */
  403. protected function checkStatus() {
  404. if ($this->memoryExceeded()) {
  405. return MigrationInterface::RESULT_INCOMPLETE;
  406. }
  407. return MigrationInterface::RESULT_COMPLETED;
  408. }
  409. /**
  410. * Tests whether we've exceeded the desired memory threshold.
  411. *
  412. * If so, output a message.
  413. *
  414. * @return bool
  415. * TRUE if the threshold is exceeded, otherwise FALSE.
  416. */
  417. protected function memoryExceeded() {
  418. $usage = $this->getMemoryUsage();
  419. $pct_memory = $usage / $this->memoryLimit;
  420. if (!$threshold = $this->memoryThreshold) {
  421. return FALSE;
  422. }
  423. if ($pct_memory > $threshold) {
  424. $this->message->display(
  425. $this->t(
  426. 'Memory usage is @usage (@pct% of limit @limit), reclaiming memory.',
  427. [
  428. '@pct' => round($pct_memory * 100),
  429. '@usage' => $this->formatSize($usage),
  430. '@limit' => $this->formatSize($this->memoryLimit),
  431. ]
  432. ),
  433. 'warning'
  434. );
  435. $usage = $this->attemptMemoryReclaim();
  436. $pct_memory = $usage / $this->memoryLimit;
  437. // Use a lower threshold - we don't want to be in a situation where we keep
  438. // coming back here and trimming a tiny amount
  439. if ($pct_memory > (0.90 * $threshold)) {
  440. $this->message->display(
  441. $this->t(
  442. 'Memory usage is now @usage (@pct% of limit @limit), not enough reclaimed, starting new batch',
  443. [
  444. '@pct' => round($pct_memory * 100),
  445. '@usage' => $this->formatSize($usage),
  446. '@limit' => $this->formatSize($this->memoryLimit),
  447. ]
  448. ),
  449. 'warning'
  450. );
  451. return TRUE;
  452. }
  453. else {
  454. $this->message->display(
  455. $this->t(
  456. 'Memory usage is now @usage (@pct% of limit @limit), reclaimed enough, continuing',
  457. [
  458. '@pct' => round($pct_memory * 100),
  459. '@usage' => $this->formatSize($usage),
  460. '@limit' => $this->formatSize($this->memoryLimit),
  461. ]
  462. ),
  463. 'warning');
  464. return FALSE;
  465. }
  466. }
  467. else {
  468. return FALSE;
  469. }
  470. }
  471. /**
  472. * Returns the memory usage so far.
  473. *
  474. * @return int
  475. * The memory usage.
  476. */
  477. protected function getMemoryUsage() {
  478. return memory_get_usage();
  479. }
  480. /**
  481. * Tries to reclaim memory.
  482. *
  483. * @return int
  484. * The memory usage after reclaim.
  485. */
  486. protected function attemptMemoryReclaim() {
  487. // First, try resetting Drupal's static storage - this frequently releases
  488. // plenty of memory to continue.
  489. drupal_static_reset();
  490. // Entity storage can blow up with caches so clear them out.
  491. $manager = \Drupal::entityManager();
  492. foreach ($manager->getDefinitions() as $id => $definition) {
  493. $manager->getStorage($id)->resetCache();
  494. }
  495. // @TODO: explore resetting the container.
  496. // Run garbage collector to further reduce memory.
  497. gc_collect_cycles();
  498. return memory_get_usage();
  499. }
  500. /**
  501. * Generates a string representation for the given byte count.
  502. *
  503. * @param int $size
  504. * A size in bytes.
  505. *
  506. * @return string
  507. * A translated string representation of the size.
  508. */
  509. protected function formatSize($size) {
  510. return format_size($size);
  511. }
  512. }