MediaWiki
REL1_22
|
00001 <?php 00038 class StatCounter { 00040 protected $deltas = array(); // (key => count) 00041 00042 protected function __construct() {} 00043 00047 public static function singleton() { 00048 static $instance = null; 00049 if ( !$instance ) { 00050 $instance = new self(); 00051 } 00052 return $instance; 00053 } 00054 00062 public function incr( $key, $count = 1 ) { 00063 $this->deltas[$key] = isset( $this->deltas[$key] ) ? $this->deltas[$key] : 0; 00064 $this->deltas[$key] += $count; 00065 if ( PHP_SAPI === 'cli' ) { 00066 $this->flush(); 00067 } 00068 } 00069 00075 public function flush() { 00076 global $wgStatsMethod; 00077 00078 $deltas = array_filter( $this->deltas ); // remove 0 valued entries 00079 if ( $wgStatsMethod === 'udp' ) { 00080 $this->sendDeltasUDP( $deltas ); 00081 } elseif ( $wgStatsMethod === 'cache' ) { 00082 $this->sendDeltasMemc( $deltas ); 00083 } else { 00084 // disabled 00085 } 00086 $this->deltas = array(); 00087 } 00088 00093 protected function sendDeltasUDP( array $deltas ) { 00094 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgAggregateStatsID, 00095 $wgStatsFormatString; 00096 00097 $id = strlen( $wgAggregateStatsID ) ? $wgAggregateStatsID : wfWikiID(); 00098 00099 $lines = array(); 00100 foreach ( $deltas as $key => $count ) { 00101 $lines[] = sprintf( $wgStatsFormatString, $id, $count, $key ); 00102 } 00103 00104 if ( count( $lines ) ) { 00105 static $socket = null; 00106 if ( !$socket ) { 00107 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP ); 00108 } 00109 $packet = ''; 00110 $packets = array(); 00111 foreach ( $lines as $line ) { 00112 if ( ( strlen( $packet ) + strlen( $line ) ) > 1450 ) { 00113 $packets[] = $packet; 00114 $packet = ''; 00115 } 00116 $packet .= $line; 00117 } 00118 if ( $packet != '' ) { 00119 $packets[] = $packet; 00120 } 00121 foreach ( $packets as $packet ) { 00122 wfSuppressWarnings(); 00123 socket_sendto( 00124 $socket, 00125 $packet, 00126 strlen( $packet ), 00127 0, 00128 $wgUDPProfilerHost, 00129 $wgUDPProfilerPort 00130 ); 00131 wfRestoreWarnings(); 00132 } 00133 } 00134 } 00135 00140 protected function sendDeltasMemc( array $deltas ) { 00141 global $wgMemc; 00142 00143 foreach ( $deltas as $key => $count ) { 00144 $ckey = wfMemcKey( 'stats', $key ); 00145 if ( $wgMemc->incr( $ckey, $count ) === null ) { 00146 $wgMemc->add( $ckey, $count ); 00147 } 00148 } 00149 } 00150 }