00001 <?php
00002
00003 require( 'Net/Gearman/Client.php' );
00004 require( 'Net/Gearman/Worker.php' );
00005
00006 class MWGearmanJob extends Net_Gearman_Job_Common {
00007 function switchWiki( $wiki, $params ) {
00008 echo "Switching to $wiki\n";
00009
00010 # Pretend that we have completed it right now, because the new process won't do it
00011 $this->complete( array( 'result' => true ) );
00012 socket_close( $this->conn );
00013
00014 # Close some more sockets
00015 wfGetLBFactory()->shutdown();
00016 global $wgMemc;
00017 $wgMemc->disconnect_all();
00018
00019 # Find PHP
00020 $php = readlink( '/proc/' . posix_getpid() . '/exe' );
00021
00022 # Run the worker script
00023 $args = array( $_SERVER['PHP_SELF'],
00024 '--wiki', $wiki,
00025 '--fake-job', serialize( $params ) );
00026 $args = array_merge( $args, $GLOBALS['args'] );
00027 pcntl_exec( $php, $args, $_ENV );
00028 echo "Error running exec\n";
00029 }
00030
00031 function run( $params ) {
00032 if ( wfWikiID() !== $params['wiki'] ) {
00033 $this->switchWiki( $params['wiki'], $params );
00034 }
00035 return self::runNoSwitch( $params );
00036 }
00037
00038 static function runNoSwitch( $params ) {
00039 echo implode( ' ', $params ) . "\n";
00040 $title = Title::newFromText( $params['title'] );
00041 $mwJob = Job::factory( $params['command'], $title, $params['params'] );
00042 return $mwJob->run();
00043 }
00044 }
00045
00046 class NonScaryGearmanWorker extends Net_Gearman_Worker {
00047
00052 protected function doWork($socket) {
00053 Net_Gearman_Connection::send($socket, 'grab_job');
00054
00055 $resp = array('function' => 'noop');
00056 while (count($resp) && $resp['function'] == 'noop') {
00057 $resp = Net_Gearman_Connection::blockingRead($socket);
00058 }
00059
00060 if (in_array($resp['function'], array('noop', 'no_job'))) {
00061 return false;
00062 }
00063
00064 if ($resp['function'] != 'job_assign') {
00065 throw new Net_Gearman_Exception('Holy Cow! What are you doing?!');
00066 }
00067
00068 $name = $resp['data']['func'];
00069 $handle = $resp['data']['handle'];
00070 $arg = array();
00071
00072 if (isset($resp['data']['arg']) &&
00073 Net_Gearman_Connection::stringLength($resp['data']['arg'])) {
00074 $arg = json_decode($resp['data']['arg'], true);
00075 }
00076
00077 ### START MW DIFFERENT BIT
00078 if ( $name != 'mw_job' ) {
00079 throw new Net_Gearman_Job_Exception('Invalid function');
00080 }
00081 $job = new MWGearmanJob($socket, $handle);
00082 ### END MW DIFFERENT BIT
00083
00084 try {
00085 $this->start($handle, $name, $arg);
00086 $res = $job->run($arg);
00087 if (!is_array($res)) {
00088 $res = array('result' => $res);
00089 }
00090
00091 $job->complete($res);
00092 $this->complete($handle, $name, $res);
00093 } catch (Net_Gearman_Job_Exception $e) {
00094 $job->fail();
00095 $this->fail($handle, $name, $e);
00096 }
00097
00098
00099 $job = null;
00100
00101 return true;
00102 }
00103 }
00104