summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/maintenance/rebuildElasticIndex.php
blob: fe48d734f3dcb5136a48c0097b1c33094e8f6ac8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php

namespace SMW\Maintenance;

use SMW\ApplicationFactory;
use SMW\SQLStore\SQLStore;
use SMW\Elastic\ElasticFactory;
use SMW\Setup;

$basePath = getenv( 'MW_INSTALL_PATH' ) !== false ? getenv('MW_INSTALL_PATH' ) : __DIR__ . '/../../..';

require_once $basePath . '/maintenance/Maintenance.php';

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class RebuildElasticIndex extends \Maintenance {

	/**
	 * @var Store
	 */
	private $store;

	/**
	 * @var Rebuilder
	 */
	private $rebuilder;

	/**
	 * @var JobQueue
	 */
	private $jobQueue;

	/**
	 * @see Maintenance::__construct
	 *
	 * @since 3.0
	 */
	public function __construct() {
		$this->mDescription = 'Rebuild the Elasticsearch index from property tables (content is not explicitly parsed!)';
		$this->addOption( 's', 'Start with a selected document no.', false, true );
		$this->addOption( 'e', 'End with a selected document no. (requires a start ID)', false, true );
		$this->addOption( 'page', 'Set of pages (Foo|Bar|...)', false, true );
		$this->addOption( 'update-settings', 'Update settings and mappings for listed indices', false, false );
		$this->addOption( 'force-refresh', 'Forces a refresh of listed indices', false, false );
		$this->addOption( 'delete-all', 'Delete listed indices without rebuilding the data', false, false );
		$this->addOption( 'skip-fileindex', 'Skipping any file ingest actions', false, false );
		$this->addOption( 'run-fileindex', 'Only run file ingest actions', false, false );

		$this->addOption( 'debug', 'Sets global variables to support debug ouput while running the script', false );
		$this->addOption( 'report-runtime', 'Report execution time and memory usage', false );

		parent::__construct();
	}

	/**
	 * @since 3.0
	 *
	 * @param string $message
	 */
	public function reportMessage( $message ) {
		$this->output( $message );
	}

	/**
	 * @see Maintenance::execute
	 */
	public function execute() {

		if ( !Setup::isEnabled() ) {
			$this->output( "You need to have SMW enabled in order to use this maintenance script!\n\n" );
			exit;
		}

		if ( !Setup::isValid( true ) ) {
			$this->reportMessage( "\nYou need to run `update.php` or `setupStore.php` first before continuing\nwith any maintenance tasks!\n" );
			exit;
		}

		// If available, set a callback to listen to a possible user termination
		// and try to recover the index settings.
		if ( function_exists( 'pcntl_signal_dispatch' ) ) {
			pcntl_signal( SIGTERM, [ $this, 'handleTermSignal' ], false );
			pcntl_signal_dispatch();
		}

		$applicationFactory = ApplicationFactory::getInstance();
		$maintenanceFactory = $applicationFactory->newMaintenanceFactory();

		$maintenanceHelper = $maintenanceFactory->newMaintenanceHelper();
		$maintenanceHelper->initRuntimeValues();

		if ( $this->hasOption( 'debug' ) ) {
			$maintenanceHelper->setGlobalToValue( 'wgShowExceptionDetails', true );
			$maintenanceHelper->setGlobalToValue( 'wgShowSQLErrors', true );
			$maintenanceHelper->setGlobalToValue( 'wgShowDBErrorBacktrace', true );
		} else {
			$maintenanceHelper->setGlobalToValue( 'wgDebugLogFile', '' );
			$maintenanceHelper->setGlobalToValue( 'wgDebugLogGroups', [] );
		}

		$this->jobQueue = $applicationFactory->getJobQueue();
		$this->store = $applicationFactory->getStore( 'SMW\SQLStore\SQLStore' );
		$elasticFactory = $applicationFactory->create( 'ElasticFactory' );

		$this->rebuilder = $elasticFactory->newRebuilder(
			$this->store
		);

		$this->rebuilder->setMessageReporter(
			$maintenanceFactory->newMessageReporter( [ $this, 'reportMessage' ] )
		);

		if ( !$this->rebuilder->ping() ) {
			return $this->reportMessage(
				"\n" . 'Elasticsearch endpoint(s) are not available!' . "\n"
			);
		}

		$this->reportMessage(
			"\nThe script rebuilds the index from available property tables. Any\n" .
			"change of the index rules (e.g. altered stopwords, new stemmer etc.)\n" .
			"or a newly added (or altered) table requires to run this script again\n" .
			"to ensure that the index complies with the rules set forth by the SQL\n" .
			"back-end or the Elasticsearch field mapping.\n"
		);

		if ( $this->otherActivities() ) {
			return true;
		}

		$this->showAbort();

		$this->reportMessage(
			"\nIf for some reason the rebuild process is aborted, please make sure\n" .
			"to run `--update-settings` so that default settings can be recovered\n".
			"and set to a normal working mode.\n"
		);

		$this->rebuild();

		if ( $this->hasOption( 'report-runtime' ) ) {
			$this->reportMessage( "\n" . $maintenanceHelper->getFormattedRuntimeValues() . "\n" );
		}

		$maintenanceHelper->reset();

		return true;
	}

	/**
	 * @see Maintenance::addDefaultParams
	 *
	 * @since 3.0
	 */
	protected function addDefaultParams() {
		parent::addDefaultParams();
	}

	protected function handleTermSignal( $signal ) {

		$this->reportMessage( "\n" . '   ... rebuild was terminated, start recovery process ...' );
		$this->rebuilder->setDefaults();
		$this->rebuilder->refresh();
		$this->reportMessage( "\n" . '   ... done.' . "\n" );

		pcntl_signal( SIGTERM, SIG_DFL );
		exit( 1 );
	}

	private function otherActivities() {

		if ( $this->hasOption( 'update-settings' ) ) {
			$this->reportMessage(
				"\n" . 'Settings and mappings ...'
			);

			$message = $this->rebuilder->setDefaults() ? '   ... done.' : '   ... failed (due to missing index).';
			$this->reportMessage( "\n$message\n" );

			return true;
		}

		if ( $this->hasOption( 'force-refresh' ) ) {
			$this->reportMessage(
				"\n" . 'Forcing refresh of known indices ...'
			);

			$message = $this->rebuilder->refresh() ? '   ... done.' : '   ... failed (due to missing index).';
			$this->reportMessage( "\n$message\n" );

			return true;
		}

		if ( $this->hasOption( 'delete-all' ) ) {
			$this->reportMessage(
				"\n" . 'Deleting all indices ...'
			);

			$this->rebuilder->deleteAndSetupIndices();
			$this->reportMessage( "\n   ... done.\n" );

			return true;
		}

		return false;
	}

	private function showAbort() {

		$showAbort = !$this->hasOption( 'quick' ) && !$this->hasOption( 's' ) && !$this->hasOption( 'page' ) && !$this->hasOption( 'run-fileindex' );

		if ( !$showAbort ) {
			return;
		}

		$this->reportMessage(
			"\nThe rebuild will use a rollover approach which means that while the\n" .
			"new index is created, the old index is still available and allows\n" .
			"queries to work even though the rebuild is ongoing. Once completed,\n" .
			"a \"rollover\" will switch the indices at which point the old indices\n" .
			"are being removed.\n"
		);

		$this->reportMessage(
			"\nIt should be noted that the replication is paused for the duration\n" .
			"of the rebuild to allow changes to pages and annotations to be\n" .
			"processed after the re-index has been completed therefore running\n".
			"the job scheduler is obligatory.\n"
		);

		$this->reportMessage( "\n" . 'Abort the rebuild with control-c in the next five seconds ...  ' );
		swfCountDown( 5 );
	}

	private function rebuild() {

		$this->reportMessage( "\nRebuilding indices ..." );
		$isSelective = $this->hasOption( 's' ) || $this->hasOption( 'page' );

		if ( !$this->hasOption( 's' ) && !$this->hasOption( 'page' ) && !$this->hasOption( 'run-fileindex' ) ) {
			$this->reportMessage( "\n" . '   ... creating required indices and aliases ...' );
			$this->rebuilder->createIndices();
		}

		$this->rebuilder->prepare();

		list( $res, $last ) = $this->rebuilder->select(
			$this->store,
			$this->select_conditions()
		);

		if ( $isSelective ) {
			$last = $res->numRows();
		}

		if ( $res->numRows() > 0 ) {
			$this->reportMessage( "\n" );
		} else {
			$this->reportMessage( "\n" . '   ... no documents to process ...' );
		}

		$this->rebuilder->set( 'skip-fileindex', $this->getOption( 'skip-fileindex' ) );
		$i = 0;

		foreach ( $res as $row ) {
			$i++;
			$this->rebuild_row( $i, $row, $last, $isSelective );
		}

		$this->rebuilder->setDefaults();
		$this->rebuilder->refresh();

		$this->reportMessage( "\n" . '   ... done.' . "\n" );

		if ( ( $count = $this->jobQueue->getQueueSize( 'smw.elasticIndexerRecovery' ) ) > 0 ) {
			$this->reportMessage( "\n" . "Job queue ..." );
			$this->reportMessage( "\n" . "   ... smw.elasticIndexerRecovery has $count unprocessed jobs ..." );
			$this->reportMessage( "\n" . '   ... done.' . "\n" );
		}
	}

	private function rebuild_row( $i, $row, $last, $isSelective ) {

		$i = $isSelective ? $i : $row->smw_id;
		$key = $isSelective ? '(count)' : 'no.';

		$this->reportMessage(
			"\r". sprintf( "%-50s%s", "   ... updating document $key", sprintf( "%4.0f%% (%s/%s)", ( $i / $last ) * 100, $i, $last ) )
		);

		if ( $row->smw_iw === SMW_SQL3_SMWDELETEIW || $row->smw_iw === SMW_SQL3_SMWREDIIW ) {
			return $this->rebuilder->delete( $row->smw_id );
		}

		$dataItem = $this->store->getObjectIds()->getDataItemById(
			$row->smw_id
		);

		if ( $dataItem === null ) {
			return;
		}

		$this->rebuilder->rebuild(
			$row->smw_id,
			$this->store->getSemanticData( $dataItem )
		);
	}

	private function select_conditions() {

		$connection = $this->store->getConnection( 'mw.db' );

		$conditions = [];
		$conditions[] = "smw_iw!=" . $connection->addQuotes( SMW_SQL3_SMWIW_OUTDATED );

		if ( $this->hasOption( 's' ) ) {
			$conditions[] = 'smw_id >= ' . $connection->addQuotes( $this->getOption( 's' ) );

			if ( $this->hasOption( 'e' ) ) {
				$conditions[] = 'smw_id <= ' . $connection->addQuotes( $this->getOption( 'e' ) );
			}
		}

		if ( $this->hasOption( 'run-fileindex' ) ) {
			$conditions[] = 'smw_namespace=' . $connection->addQuotes( NS_FILE );
		}

		if ( $this->hasOption( 'page' ) ) {
			$pages = explode( '|', $this->getOption( 'page' ) );

			foreach ( $pages as $page ) {
				$title = \Title::newFromText( $page );

				if ( $title === null ) {
					continue;
				}

				$op = '=';
				$text = $title->getDBKey();

				// Match something like --page="Lorem*"
				if ( strpos( $title->getDBKey(), '*' ) !== false ) {
					$op = ' LIKE ';
					$text = str_replace( '*', '%', $text );
				}

				$cond = [
					"smw_title$op" . $connection->addQuotes( $text ),
					'smw_namespace=' . $connection->addQuotes( $title->getNamespace() )
				];

				$conditions[] = implode( ' AND ', $cond );
			}
		}

		return $conditions;
	}

}

$maintClass = 'SMW\Maintenance\RebuildElasticIndex';
require_once( RUN_MAINTENANCE_IF_MAIN );