Debian Codegraph @

includes/installer/Pingback.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Installer;
22
23 use MediaWiki\Config\Config;
24 use MediaWiki\Http\HttpRequestFactory;
25 use MediaWiki\Json\FormatJson;
26 use MediaWiki\MainConfigNames;
27 use MWCryptRand;
28 use Psr\Log\LoggerInterface;
29 use Wikimedia\ObjectCache\BagOStuff;
30 use Wikimedia\Rdbms\DBError;
31 use Wikimedia\Rdbms\IConnectionProvider;
32 use Wikimedia\Timestamp\ConvertibleTimestamp;
33
34 /**
35 * Send information about this MediaWiki instance to mediawiki.org.
36 *
37 * This service uses two kinds of rows in the `update_log` database table:
38 *
39 * - ul_key `PingBack`, this holds a random identifier for this wiki,
40 * created only once, when the first ping after wiki creation is sent.
41 * - ul_key `Pingback-<MW_VERSION>`, this holds a timestamp and is created
42 * once after each MediaWiki upgrade, and then updated up to once a month.
43 *
44 * @internal For use by Setup.php only
45 * @since 1.28
46 */
47 class Pingback {
48
49 /**
50 * @var string The name of the Legacy EventLogging schema that Pingback used to use.
51 */
52 private const LEGACY_EVENTLOGGING_SCHEMA = 'MediaWikiPingback';
53
54 /**
55 * @var string The versioned schema with which the Pingback events will be validated.
56 *
57 * All versions of the schema live at
58 * {@link https://schema.wikimedia.org/#!//secondary/jsonschema/analytics/legacy/mediawikipingback}.
59 */
60 private const EVENT_PLATFORM_SCHEMA_ID = '/analytics/legacy/mediawikipingback/1.0.0';
61
62 /**
63 * @var string The name of the Event Platform stream to submit the event to.
64 *
65 * By convention, we derive the name of an Event Platform stream corresponding to a Legacy
66 * EventLogging schema by prepending "eventlogging_" to it, i.e.
67 * "FooSchema" -> "eventlogging_FooSchema". This convention is codified in
68 * {@link https://gerrit.wikimedia.org/g/mediawiki/extensions/EventLogging/+/d47dbc10455bcb6dbc98a49fa169f75d6131c3da/includes/EventLogging.php#298}.
69 *
70 * @see Pingback::LEGACY_EVENTLOGGING_SCHEMA
71 */
72 private const EVENT_PLATFORM_STREAM = 'eventlogging_MediaWikiPingback';
73
74 /** @var string */
75 private const EVENT_PLATFORM_EVENT_INTAKE_SERVICE_URI =
76 'https://intake-analytics.wikimedia.org/v1/events?hasty=true';
77
78 /** @var LoggerInterface */
79 protected $logger;
80 /** @var Config */
81 protected $config;
82 /** @var IConnectionProvider */
83 protected $dbProvider;
84 /** @var BagOStuff */
85 protected $cache;
86 /** @var HttpRequestFactory */
87 protected $http;
88 /** @var string updatelog key (also used as cache/db lock key) */
89 protected $key;
90 /** @var string */
91 protected $eventIntakeUri;
92
93 /**
94 * @param Config $config
95 * @param IConnectionProvider $dbProvider
96 * @param BagOStuff $cache
97 * @param HttpRequestFactory $http
98 * @param LoggerInterface $logger
99 */
100 public function __construct(
101 Config $config,
102 IConnectionProvider $dbProvider,
103 BagOStuff $cache,
104 HttpRequestFactory $http,
105 LoggerInterface $logger,
106 string $eventIntakeUrl = self::EVENT_PLATFORM_EVENT_INTAKE_SERVICE_URI
107 ) {
108 $this->config = $config;
109 $this->dbProvider = $dbProvider;
110 $this->cache = $cache;
111 $this->http = $http;
112 $this->logger = $logger;
113 $this->key = 'Pingback-' . MW_VERSION;
114 $this->eventIntakeUri = $eventIntakeUrl;
115 }
116
117 /**
118 * Maybe send a ping.
119 *
120 * @throws DBError If identifier insert fails
121 * @throws DBError If timestamp upsert fails
122 */
123 public function run(): void {
124 if ( !$this->config->get( MainConfigNames::Pingback ) ) {
125 // disabled
126 return;
127 }
128 if ( $this->wasRecentlySent() ) {
129 // already sent recently
130 return;
131 }
132 if ( !$this->acquireLock() ) {
133 $this->logger->debug( __METHOD__ . ": couldn't acquire lock" );
134 return;
135 }
136
137 $data = $this->getData();
138 if ( !$this->postPingback( $data ) ) {
139 $this->logger->warning( __METHOD__ . ": failed to send; check 'http' log channel" );
140 return;
141 }
142
143 // Record the fact that we have sent a pingback for this MediaWiki version,
144 // so we don't submit data multiple times.
145 $dbw = $this->dbProvider->getPrimaryDatabase();
146 $timestamp = ConvertibleTimestamp::time();
147 $dbw->newInsertQueryBuilder()
148 ->insertInto( 'updatelog' )
149 ->row( [ 'ul_key' => $this->key, 'ul_value' => $timestamp ] )
150 ->onDuplicateKeyUpdate()
151 ->uniqueIndexFields( [ 'ul_key' ] )
152 ->set( [ 'ul_value' => $timestamp ] )
153 ->caller( __METHOD__ )->execute();
154 $this->logger->debug( __METHOD__ . ": pingback sent OK ({$this->key})" );
155 }
156
157 /**
158 * Was a pingback sent in the last month for this MediaWiki version?
159 *
160 * @return bool
161 */
162 private function wasRecentlySent(): bool {
163 $timestamp = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
164 ->select( 'ul_value' )
165 ->from( 'updatelog' )
166 ->where( [ 'ul_key' => $this->key ] )
167 ->caller( __METHOD__ )->fetchField();
168 if ( $timestamp === false ) {
169 return false;
170 }
171 // send heartbeat ping if the last ping was over a month ago
172 if ( ConvertibleTimestamp::time() - (int)$timestamp > 60 * 60 * 24 * 30 ) {
173 return false;
174 }
175 return true;
176 }
177
178 /**
179 * Acquire lock for sending a pingback
180 *
181 * This ensures only one thread can attempt to send a pingback at any given
182 * time and that we wait an hour before retrying failed attempts.
183 *
184 * @return bool Whether lock was acquired
185 */
186 private function acquireLock(): bool {
187 $cacheKey = $this->cache->makeKey( 'pingback', $this->key );
188 if ( !$this->cache->add( $cacheKey, 1, $this->cache::TTL_HOUR ) ) {
189 // throttled
190 return false;
191 }
192
193 $dbw = $this->dbProvider->getPrimaryDatabase();
194 if ( !$dbw->lock( $this->key, __METHOD__, 0 ) ) {
195 // already in progress
196 return false;
197 }
198
199 return true;
200 }
201
202 /**
203 * Get the event to be sent to the server.
204 *
205 * Note well that, as well as the pingback data, only those fields required by the Event Platform are set (see
206 * <https://wikitech.wikimedia.org/wiki/Event_Platform/Schemas/Guidelines#Required_fields>).
207 *
208 * @throws DBError If identifier insert fails
209 * @return array
210 */
211 protected function getData(): array {
212 $wiki = $this->fetchOrInsertId();
213
214 return [
215 'event' => self::getSystemInfo( $this->config ),
216 'schema' => self::LEGACY_EVENTLOGGING_SCHEMA,
217 'wiki' => $wiki,
218
219 // This would be added by
220 // https://gerrit.wikimedia.org/g/mediawiki/extensions/EventLogging/+/d47dbc10455bcb6dbc98a49fa169f75d6131c3da/includes/EventLogging.php#274
221 // onwards.
222 '$schema' => self::EVENT_PLATFORM_SCHEMA_ID,
223 'client_dt' => ConvertibleTimestamp::now( TS_ISO_8601 ),
224
225 // This would be added by
226 // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/EventLogging/+/d47dbc10455bcb6dbc98a49fa169f75d6131c3da/includes/EventSubmitter/EventBusEventSubmitter.php#81
227 // onwards.
228 'meta' => [
229 'stream' => self::EVENT_PLATFORM_STREAM,
230 ],
231 ];
232 }
233
234 /**
235 * Collect basic data about this MediaWiki installation and return it
236 * as an associative array conforming to the MediaWikiPingback event schema at
237 * <https://gerrit.wikimedia.org/r/plugins/gitiles/schemas/event/secondary/+/refs/heads/master/jsonschema/analytics/legacy/mediawikipingback/>.
238 *
239 * Developers: If you're adding a new piece of data to this, please document
240 * this data at <https://www.mediawiki.org/wiki/Manual:$wgPingback>.
241 *
242 * @internal For use by Installer only to display which data we send.
243 * @param Config $config With `DBtype` set.
244 * @return array
245 */
246 public static function getSystemInfo( Config $config ): array {
247 $event = [
248 'database' => $config->get( MainConfigNames::DBtype ),
249 'MediaWiki' => MW_VERSION,
250 'PHP' => PHP_VERSION,
251 'OS' => PHP_OS . ' ' . php_uname( 'r' ),
252 'arch' => PHP_INT_SIZE === 8 ? 64 : 32,
253 'machine' => php_uname( 'm' ),
254 ];
255
256 if ( isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
257 $event['serverSoftware'] = $_SERVER['SERVER_SOFTWARE'];
258 }
259
260 $limit = ini_get( 'memory_limit' );
261 if ( $limit && $limit !== "-1" ) {
262 $event['memoryLimit'] = $limit;
263 }
264
265 return $event;
266 }
267
268 /**
269 * Get a unique, stable identifier for this wiki
270 *
271 * If the identifier does not already exist, create it and save it in the
272 * database. The identifier is randomly-generated.
273 *
274 * @throws DBError If identifier insert fails
275 * @return string 32-character hex string
276 */
277 private function fetchOrInsertId(): string {
278 // We've already obtained a primary connection for the lock, and plan to do a write.
279 // But, still prefer reading this immutable value from a replica to reduce load.
280 $id = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
281 ->select( 'ul_value' )
282 ->from( 'updatelog' )
283 ->where( [ 'ul_key' => 'PingBack' ] )
284 ->caller( __METHOD__ )->fetchField();
285 if ( $id !== false ) {
286 return $id;
287 }
288
289 $dbw = $this->dbProvider->getPrimaryDatabase();
290 $id = $dbw->newSelectQueryBuilder()
291 ->select( 'ul_value' )
292 ->from( 'updatelog' )
293 ->where( [ 'ul_key' => 'PingBack' ] )
294 ->caller( __METHOD__ )->fetchField();
295 if ( $id !== false ) {
296 return $id;
297 }
298
299 $id = MWCryptRand::generateHex( 32 );
300 $dbw->newInsertQueryBuilder()
301 ->insertInto( 'updatelog' )
302 ->row( [ 'ul_key' => 'PingBack', 'ul_value' => $id ] )
303 ->caller( __METHOD__ )->execute();
304 return $id;
305 }
306
307 /**
308 * Serialize the pingback data and submit it to the Event Platform (see
309 * <https://wikitech.wikimedia.org/wiki/Event_Platform>).
310 *
311 * Compare:
312 * <https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/EventLogging/+/933b62f29d68f/includes/EventSubmitter/EventBusEventSubmitter.php#33>
313 *
314 * The schema for the event is located at:
315 * <https://schema.wikimedia.org/repositories/secondary/jsonschema/analytics/legacy/mediawikipingback/1.0.0>
316 *
317 * @param array $data Pingback data as an associative array
318 * @return bool
319 */
320 private function postPingback( array $data ): bool {
321 $request = $this->http->create( $this->eventIntakeUri, [
322 'method' => 'POST',
323 'postData' => FormatJson::encode( $data ),
324 ], __METHOD__ );
325 $request->setHeader( 'Content-Type', 'application/json' );
326
327 $result = $request->execute();
328
329 return $result->isGood();
330 }
331 }
332
333 /** @deprecated class alias since 1.41 */
334 class_alias( Pingback::class, 'Pingback' );