batch.inc

  1. 8.0.x includes/batch.inc
  2. 8.0.x commands/core/drupal/batch.inc
  3. 6.x includes/batch.inc
  4. 6.x commands/core/drupal/batch.inc
  5. 7.x includes/batch.inc
  6. 7.x commands/core/drupal/batch.inc
  7. 3.x includes/batch.inc
  8. 4.x commands/core/drupal/batch.inc
  9. 4.x includes/batch.inc
  10. 5.x commands/core/drupal/batch.inc
  11. 5.x includes/batch.inc
  12. master commands/core/drupal/batch.inc
  13. master includes/batch.inc

Drupal 7 engine for the Batch API

Functions

Namesort descending Description
_drush_backend_batch_process Main loop for the Drush batch API.
_drush_batch_command Initialize the batch command and call the worker function.
_drush_batch_finished End the batch processing: Call the 'finished' callbacks to allow custom handling of results, and resolve page redirection.
_drush_batch_shutdown Shutdown function: store the batch data for next request, or clear the table if the batch is finished.
_drush_batch_worker Process batch operations

File

commands/core/drupal/batch.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Drupal 7 engine for the Batch API
  5. */
  6. use Drush\Log\LogLevel;
  7. /**
  8. * Main loop for the Drush batch API.
  9. *
  10. * Saves a record of the batch into the database, and progressively call $command to
  11. * process the operations.
  12. *
  13. * @param command
  14. * The command to call to process the batch.
  15. *
  16. */
  17. function _drush_backend_batch_process($command = 'batch-process', $args, $options) {
  18. $batch =& batch_get();
  19. if (isset($batch)) {
  20. $process_info = array(
  21. 'current_set' => 0,
  22. );
  23. $batch += $process_info;
  24. // The batch is now completely built. Allow other modules to make changes
  25. // to the batch so that it is easier to reuse batch processes in other
  26. // enviroments.
  27. if (drush_drupal_major_version() >= 8) {
  28. \Drupal::moduleHandler()->alter('batch', $batch);
  29. }
  30. else {
  31. drupal_alter('batch', $batch);
  32. }
  33. // Assign an arbitrary id: don't rely on a serial column in the 'batch'
  34. // table, since non-progressive batches skip database storage completely.
  35. $batch['id'] = db_next_id();
  36. $args[] = $batch['id'];
  37. $batch['progressive'] = TRUE;
  38. // Move operations to a job queue. Non-progressive batches will use a
  39. // memory-based queue.
  40. foreach ($batch['sets'] as $key => $batch_set) {
  41. _batch_populate_queue($batch, $key);
  42. }
  43. drush_include_engine('drupal', 'environment');
  44. // Store the batch.
  45. db_insert('batch')
  46. ->fields(array(
  47. 'bid' => $batch['id'],
  48. 'timestamp' => REQUEST_TIME,
  49. 'token' => drush_get_token($batch['id']),
  50. 'batch' => serialize($batch),
  51. ))
  52. ->execute();
  53. $finished = FALSE;
  54. // Not used in D8+ and possibly earlier.
  55. global $user;
  56. while (!$finished) {
  57. $data = drush_invoke_process('@self', $command, $args, array($batch['id'], '-u', drush_user_get_class()->getCurrentUserAsSingle()->id()));
  58. $finished = drush_get_error() || !$data || (isset($data['context']['drush_batch_process_finished']) && $data['context']['drush_batch_process_finished'] == TRUE);
  59. }
  60. }
  61. }
  62. /**
  63. * Initialize the batch command and call the worker function.
  64. *
  65. * Loads the batch record from the database and sets up the requirements
  66. * for the worker, such as registering the shutdown function.
  67. *
  68. * @param id
  69. * The batch id of the batch being processed.
  70. */
  71. function _drush_batch_command($id) {
  72. $batch =& batch_get();
  73. $data = db_query("SELECT batch FROM {batch} WHERE bid = :bid", array(
  74. ':bid' => $id))->fetchField();
  75. if ($data) {
  76. $batch = unserialize($data);
  77. }
  78. else {
  79. return FALSE;
  80. }
  81. if (!isset($batch['running'])) {
  82. $batch['running'] = TRUE;
  83. }
  84. // Register database update for end of processing.
  85. register_shutdown_function('_drush_batch_shutdown');
  86. if (_drush_batch_worker()) {
  87. _drush_batch_finished();
  88. }
  89. }
  90. /**
  91. * Process batch operations
  92. *
  93. * Using the current $batch process each of the operations until the batch
  94. * has been completed or half of the available memory for the process has been
  95. * reached.
  96. */
  97. function _drush_batch_worker() {
  98. $batch =& batch_get();
  99. $current_set =& _batch_current_set();
  100. $set_changed = TRUE;
  101. if (empty($current_set['start'])) {
  102. $current_set['start'] = microtime(TRUE);
  103. }
  104. $queue = _batch_queue($current_set);
  105. while (!$current_set['success']) {
  106. // If this is the first time we iterate this batch set in the current
  107. // request, we check if it requires an additional file for functions
  108. // definitions.
  109. if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
  110. include_once DRUPAL_ROOT . '/' . $current_set['file'];
  111. }
  112. $task_message = '';
  113. // Assume a single pass operation and set the completion level to 1 by
  114. // default.
  115. $finished = 1;
  116. if ($item = $queue->claimItem()) {
  117. list($function, $args) = $item->data;
  118. // Build the 'context' array and execute the function call.
  119. $batch_context = array(
  120. 'sandbox' => &$current_set['sandbox'],
  121. 'results' => &$current_set['results'],
  122. 'finished' => &$finished,
  123. 'message' => &$task_message,
  124. );
  125. // Magic wrap to catch changes to 'message' key.
  126. $batch_context = new DrushBatchContext($batch_context);
  127. call_user_func_array($function, array_merge($args, array(&$batch_context)));
  128. $finished = $batch_context['finished'];
  129. if ($finished >= 1) {
  130. // Make sure this step is not counted twice when computing $current.
  131. $finished = 0;
  132. // Remove the processed operation and clear the sandbox.
  133. $queue->deleteItem($item);
  134. $current_set['count']--;
  135. $current_set['sandbox'] = array();
  136. }
  137. }
  138. // When all operations in the current batch set are completed, browse
  139. // through the remaining sets, marking them 'successfully processed'
  140. // along the way, until we find a set that contains operations.
  141. // _batch_next_set() executes form submit handlers stored in 'control'
  142. // sets (see form_execute_handlers()), which can in turn add new sets to
  143. // the batch.
  144. $set_changed = FALSE;
  145. $old_set = $current_set;
  146. while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
  147. $current_set = &_batch_current_set();
  148. $current_set['start'] = microtime(TRUE);
  149. $set_changed = TRUE;
  150. }
  151. // At this point, either $current_set contains operations that need to be
  152. // processed or all sets have been completed.
  153. $queue = _batch_queue($current_set);
  154. // If we are in progressive mode, break processing after 1 second.
  155. if (drush_memory_limit() > 0 && (memory_get_usage() * 2) >= drush_memory_limit()) {
  156. drush_log(dt("Batch process has consumed in excess of 50% of available memory. Starting new thread"), LogLevel::BATCH);
  157. // Record elapsed wall clock time.
  158. $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  159. break;
  160. }
  161. }
  162. // Reporting 100% progress will cause the whole batch to be considered
  163. // processed. If processing was paused right after moving to a new set,
  164. // we have to use the info from the new (unprocessed) set.
  165. if ($set_changed && isset($current_set['queue'])) {
  166. // Processing will continue with a fresh batch set.
  167. $remaining = $current_set['count'];
  168. $total = $current_set['total'];
  169. $progress_message = $current_set['init_message'];
  170. $task_message = '';
  171. }
  172. else {
  173. // Processing will continue with the current batch set.
  174. $remaining = $old_set['count'];
  175. $total = $old_set['total'];
  176. $progress_message = $old_set['progress_message'];
  177. }
  178. $current = $total - $remaining + $finished;
  179. $percentage = _batch_api_percentage($total, $current);
  180. return ($percentage == 100);
  181. }
  182. /**
  183. * End the batch processing:
  184. * Call the 'finished' callbacks to allow custom handling of results,
  185. * and resolve page redirection.
  186. */
  187. function _drush_batch_finished() {
  188. $batch = &batch_get();
  189. // Execute the 'finished' callbacks for each batch set, if defined.
  190. foreach ($batch['sets'] as $batch_set) {
  191. if (isset($batch_set['finished'])) {
  192. // Check if the set requires an additional file for function definitions.
  193. if (isset($batch_set['file']) && is_file($batch_set['file'])) {
  194. include_once DRUPAL_ROOT . '/' . $batch_set['file'];
  195. }
  196. if (is_callable($batch_set['finished'])) {
  197. $queue = _batch_queue($batch_set);
  198. $operations = $queue->getAllItems();
  199. $elapsed = $batch_set['elapsed'] / 1000;
  200. $elapsed = drush_drupal_major_version() >=8 ? Drupal::service('date.formatter')->formatInterval($elapsed) : format_interval($elapsed);
  201. $batch_set['finished']($batch_set['success'], $batch_set['results'], $operations, $elapsed);
  202. }
  203. }
  204. }
  205. // Clean up the batch table and unset the static $batch variable.
  206. db_delete('batch')
  207. ->condition('bid', $batch['id'])
  208. ->execute();
  209. foreach ($batch['sets'] as $batch_set) {
  210. if ($queue = _batch_queue($batch_set)) {
  211. $queue->deleteQueue();
  212. }
  213. }
  214. $_batch = $batch;
  215. $batch = NULL;
  216. drush_set_option('drush_batch_process_finished', TRUE);
  217. }
  218. /**
  219. * Shutdown function: store the batch data for next request,
  220. * or clear the table if the batch is finished.
  221. */
  222. function _drush_batch_shutdown() {
  223. if ($batch = batch_get()) {
  224. db_update('batch')
  225. ->fields(array('batch' => serialize($batch)))
  226. ->condition('bid', $batch['id'])
  227. ->execute();
  228. }
  229. }