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