Complex classes like JobRunner often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use JobRunner, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 34 | class JobRunner implements LoggerAwareInterface { |
||
| 35 | /** @var callable|null Debug output handler */ |
||
| 36 | protected $debug; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @var LoggerInterface $logger |
||
| 40 | */ |
||
| 41 | protected $logger; |
||
| 42 | |||
| 43 | const MAX_ALLOWED_LAG = 3; // abort if more than this much DB lag is present |
||
| 44 | const LAG_CHECK_PERIOD = 1.0; // check slave lag this many seconds |
||
| 45 | const ERROR_BACKOFF_TTL = 1; // seconds to back off a queue due to errors |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @param callable $debug Optional debug output handler |
||
| 49 | */ |
||
| 50 | public function setDebugHandler( $debug ) { |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @param LoggerInterface $logger |
||
| 56 | * @return void |
||
| 57 | */ |
||
| 58 | public function setLogger( LoggerInterface $logger ) { |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @param LoggerInterface $logger |
||
| 64 | */ |
||
| 65 | public function __construct( LoggerInterface $logger = null ) { |
||
| 71 | |||
| 72 | /** |
||
| 73 | * Run jobs of the specified number/type for the specified time |
||
| 74 | * |
||
| 75 | * The response map has a 'job' field that lists status of each job, including: |
||
| 76 | * - type : the job type |
||
| 77 | * - status : ok/failed |
||
| 78 | * - error : any error message string |
||
| 79 | * - time : the job run time in ms |
||
| 80 | * The response map also has: |
||
| 81 | * - backoffs : the (job type => seconds) map of backoff times |
||
| 82 | * - elapsed : the total time spent running tasks in ms |
||
| 83 | * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit, |
||
| 84 | * memory-limit) |
||
| 85 | * |
||
| 86 | * This method outputs status information only if a debug handler was set. |
||
| 87 | * Any exceptions are caught and logged, but are not reported as output. |
||
| 88 | * |
||
| 89 | * @param array $options Map of parameters: |
||
| 90 | * - type : the job type (or false for the default types) |
||
| 91 | * - maxJobs : maximum number of jobs to run |
||
| 92 | * - maxTime : maximum time in seconds before stopping |
||
| 93 | * - throttle : whether to respect job backoff configuration |
||
| 94 | * @return array Summary response that can easily be JSON serialized |
||
| 95 | */ |
||
| 96 | public function run( array $options ) { |
||
| 248 | |||
| 249 | /** |
||
| 250 | * @param Job $job |
||
| 251 | * @param BufferingStatsdDataFactory $stats |
||
| 252 | * @param float $popTime |
||
| 253 | * @return array Map of status/error/timeMs |
||
| 254 | */ |
||
| 255 | private function executeJob( Job $job, $stats, $popTime ) { |
||
| 256 | $jType = $job->getType(); |
||
| 257 | $msg = $job->toString() . " STARTING"; |
||
| 258 | $this->logger->debug( $msg ); |
||
| 259 | $this->debugCallback( $msg ); |
||
| 260 | |||
| 261 | // Run the job... |
||
| 262 | $rssStart = $this->getMaxRssKb(); |
||
| 263 | $jobStartTime = microtime( true ); |
||
| 264 | try { |
||
| 265 | $status = $job->run(); |
||
| 266 | $error = $job->getLastError(); |
||
| 267 | $this->commitMasterChanges( $job ); |
||
| 268 | |||
| 269 | DeferredUpdates::doUpdates(); |
||
| 270 | $this->commitMasterChanges( $job ); |
||
| 271 | } catch ( Exception $e ) { |
||
| 272 | MWExceptionHandler::rollbackMasterChangesAndLog( $e ); |
||
| 273 | $status = false; |
||
| 274 | $error = get_class( $e ) . ': ' . $e->getMessage(); |
||
| 275 | MWExceptionHandler::logException( $e ); |
||
| 276 | } |
||
| 277 | // Always attempt to call teardown() even if Job throws exception. |
||
| 278 | try { |
||
| 279 | $job->teardown(); |
||
| 280 | } catch ( Exception $e ) { |
||
| 281 | MWExceptionHandler::logException( $e ); |
||
| 282 | } |
||
| 283 | |||
| 284 | // Commit all outstanding connections that are in a transaction |
||
| 285 | // to get a fresh repeatable read snapshot on every connection. |
||
| 286 | // Note that jobs are still responsible for handling slave lag. |
||
| 287 | wfGetLBFactory()->commitAll( __METHOD__ ); |
||
| 288 | // Clear out title cache data from prior snapshots |
||
| 289 | LinkCache::singleton()->clear(); |
||
| 290 | $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 ); |
||
| 291 | $rssEnd = $this->getMaxRssKb(); |
||
| 292 | |||
| 293 | // Record how long jobs wait before getting popped |
||
| 294 | $readyTs = $job->getReadyTimestamp(); |
||
| 295 | if ( $readyTs ) { |
||
| 296 | $pickupDelay = max( 0, $popTime - $readyTs ); |
||
| 297 | $stats->timing( 'jobqueue.pickup_delay.all', 1000 * $pickupDelay ); |
||
| 298 | $stats->timing( "jobqueue.pickup_delay.$jType", 1000 * $pickupDelay ); |
||
| 299 | } |
||
| 300 | // Record root job age for jobs being run |
||
| 301 | $rootTimestamp = $job->getRootJobParams()['rootJobTimestamp']; |
||
| 302 | if ( $rootTimestamp ) { |
||
| 303 | $age = max( 0, $popTime - wfTimestamp( TS_UNIX, $rootTimestamp ) ); |
||
| 304 | $stats->timing( "jobqueue.pickup_root_age.$jType", 1000 * $age ); |
||
| 305 | } |
||
| 306 | // Track the execution time for jobs |
||
| 307 | $stats->timing( "jobqueue.run.$jType", $timeMs ); |
||
| 308 | // Track RSS increases for jobs (in case of memory leaks) |
||
| 309 | if ( $rssStart && $rssEnd ) { |
||
| 310 | $stats->updateCount( "jobqueue.rss_delta.$jType", $rssEnd - $rssStart ); |
||
| 311 | } |
||
| 312 | |||
| 313 | if ( $status === false ) { |
||
| 314 | $msg = $job->toString() . " t=$timeMs error={$error}"; |
||
| 315 | $this->logger->error( $msg ); |
||
| 316 | $this->debugCallback( $msg ); |
||
| 317 | } else { |
||
| 318 | $msg = $job->toString() . " t=$timeMs good"; |
||
| 319 | $this->logger->info( $msg ); |
||
| 320 | $this->debugCallback( $msg ); |
||
| 321 | } |
||
| 322 | |||
| 323 | return [ 'status' => $status, 'error' => $error, 'timeMs' => $timeMs ]; |
||
| 324 | } |
||
| 325 | |||
| 326 | /** |
||
| 327 | * @return int|null Max memory RSS in kilobytes |
||
| 328 | */ |
||
| 329 | private function getMaxRssKb() { |
||
| 334 | |||
| 335 | /** |
||
| 336 | * @param Job $job |
||
| 337 | * @return int Seconds for this runner to avoid doing more jobs of this type |
||
| 338 | * @see $wgJobBackoffThrottling |
||
| 339 | */ |
||
| 340 | private function getBackoffTimeToWait( Job $job ) { |
||
| 365 | |||
| 366 | /** |
||
| 367 | * Get the previous backoff expiries from persistent storage |
||
| 368 | * On I/O or lock acquisition failure this returns the original $backoffs. |
||
| 369 | * |
||
| 370 | * @param array $backoffs Map of (job type => UNIX timestamp) |
||
| 371 | * @param string $mode Lock wait mode - "wait" or "nowait" |
||
| 372 | * @return array Map of (job type => backoff expiry timestamp) |
||
| 373 | */ |
||
| 374 | private function loadBackoffs( array $backoffs, $mode = 'wait' ) { |
||
| 399 | |||
| 400 | /** |
||
| 401 | * Merge the current backoff expiries from persistent storage |
||
| 402 | * |
||
| 403 | * The $deltas map is set to an empty array on success. |
||
| 404 | * On I/O or lock acquisition failure this returns the original $backoffs. |
||
| 405 | * |
||
| 406 | * @param array $backoffs Map of (job type => UNIX timestamp) |
||
| 407 | * @param array $deltas Map of (job type => seconds) |
||
| 408 | * @param string $mode Lock wait mode - "wait" or "nowait" |
||
| 409 | * @return array The new backoffs account for $backoffs and the latest file data |
||
| 410 | */ |
||
| 411 | private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) { |
||
| 445 | |||
| 446 | /** |
||
| 447 | * Make sure that this script is not too close to the memory usage limit. |
||
| 448 | * It is better to die in between jobs than OOM right in the middle of one. |
||
| 449 | * @return bool |
||
| 450 | */ |
||
| 451 | private function checkMemoryOK() { |
||
| 474 | |||
| 475 | /** |
||
| 476 | * Log the job message |
||
| 477 | * @param string $msg The message to log |
||
| 478 | */ |
||
| 479 | private function debugCallback( $msg ) { |
||
| 484 | |||
| 485 | /** |
||
| 486 | * Issue a commit on all masters who are currently in a transaction and have |
||
| 487 | * made changes to the database. It also supports sometimes waiting for the |
||
| 488 | * local wiki's slaves to catch up. See the documentation for |
||
| 489 | * $wgJobSerialCommitThreshold for more. |
||
| 490 | * |
||
| 491 | * @param Job $job |
||
| 492 | * @throws DBError |
||
| 493 | */ |
||
| 494 | private function commitMasterChanges( Job $job ) { |
||
| 537 | } |
||
| 538 |
This function has been deprecated. The supplier of the file has supplied an explanatory message.
The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.