This repository was archived by the owner on Jan 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathupdate.php
More file actions
477 lines (422 loc) · 15.7 KB
/
update.php
File metadata and controls
477 lines (422 loc) · 15.7 KB
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php
/**
* Update database.
*
* @author Timo Tijhof
* @since 1.0.0
* @package TestSwarm
*/
define( 'SWARM_ENTRY', 'SCRIPT' );
require_once __DIR__ . '/../inc/init.php';
class DBUpdateScript extends MaintenanceScript {
// Versions that involve database changes
protected static $updates = array(
'1.0.0-alpha',
);
protected function init() {
$this->setDescription(
'Update the TestSwarm database from a past state to the current version.'
. ' Depending on the version, some data can not be preserved. More information'
. ' will be provided and a confirmation will be required if that is the case.'
);
$this->registerOption( 'quick', 'boolean', 'Skips questions and run the updater unconditionally.' );
}
protected function execute() {
global $swarmInstallDir;
$currentVersionFile = "$swarmInstallDir/config/version.ini";
if ( !is_readable( $currentVersionFile ) ) {
throw new SwarmException( 'version.ini is missing or unreadable.' );
}
$currentVersion = trim( file_get_contents( $currentVersionFile ) );
if ( $this->getOption( 'quick' ) ) {
$this->doDatabaseUpdates();
return;
}
$this->out( 'From which version are you upgrading? (leave empty or use --quick option to skip this)' );
$originVersion = $this->cliInput();
if ( !$originVersion ) {
$originVersion = '(auto...)';
}
// 1 => 1.0.0
$originVersion = explode( '.', $originVersion );
if ( !isset( $originVersion[1] ) ) {
$originVersion[] = '0';
}
if ( !isset( $originVersion[2] ) ) {
$originVersion[] = '0';
}
$originVersion = implode( '.', $originVersion );
$this->out(
"Update origin: $originVersion\n"
. "Current software version: $currentVersion"
);
$scheduledUpdates = array();
$scheduledUpdatesStr = '';
$prev = $originVersion;
foreach ( self::$updates as $updateTarget ) {
if ( version_compare( $updateTarget, $originVersion, '>' ) ) {
$scheduledUpdates[] = $updateTarget;
$scheduledUpdatesStr .= "* $prev -> $updateTarget\n";
$prev = $updateTarget;
}
}
if ( !count( $scheduledUpdates ) ) {
$this->out( "No updates found for $originVersion." );
$this->out( 'Do you want to run the updater anyway (use --quick to skip this)? (Y/N)' );
$quick = $this->cliInput();
if ( $quick === 'Y' ) {
$this->doDatabaseUpdates();
}
return;
}
$this->out( "Update paths:\n" . $scheduledUpdatesStr );
$this->doDatabaseUpdates();
}
/**
* The actual database updates
* Friendly reminder from http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
* - Column name must be mentioned twice in ALTER TABLE CHANGE
* - Definition must be complete
* So 'CHANGE foo BIGINT' on a 'foo INT UNSIGNED DEFAULT 1' will remove
* the default and unsigned property.
* Except for PRIMARY KEY or UNIQUE properties, those must never be
* part of a CHANGE clause.
*/
protected function doDatabaseUpdates() {
if ( $this->getContext()->dbLock() ) {
$this->error( 'Database is currently locked, please remove ./cache/database.lock before updating.' );
}
$db = $this->getContext()->getDB();
$this->out( 'Setting database.lock, other requests may not access the database during the update.' );
$this->getContext()->dbLock( true );
$this->out( 'Running tests on the database to detect which updates are needed.' );
/**
* 0.2.0 -> 1.0.0-alpha (patch-new-ua-runresults.sql)
* useragents and run_client table removed, many column changes, new runresults table.
*/
// If the previous version was before 1.0.0 we won't offer an update, because most
// changes in 1.0.0 can't be simulated without human intervention. The changes are not
// backwards compatible. Instead do a few quick checks to verify this is in fact a
// pre-1.0.0 database, then ask the user for a re-install from scratch
// (except for the users table).
$has_run_client = $db->tableExists( 'run_client' );
$has_users_request = $db->fieldExists( 'users', 'request' );
$clients_useragent_id = $db->fieldInfo( 'clients', 'useragent_id' );
if ( !$clients_useragent_id ) {
$this->unknownDatabaseState( 'clients.useragent_id not found' );
return;
}
$mysql_type_varchar = 253;
if ( !$has_run_client
&& !$has_users_request
// https://dev.mysql.com/doc/internals/en/myisam-column-attributes.html
// https://secure.php.net/mysqli_fetch_field_direct#85771
&& $clients_useragent_id->type === $mysql_type_varchar
) {
$this->out( '... run_client table already dropped' );
$this->out( '... users.request already dropped' );
$this->out( '... client.useragent_id is up to date' );
} else {
$this->out(
"\n"
. "It appears this database is from before 1.0.0. No update exists for those versions.\n"
. "The updater could re-install TestSwarm (optionally preserving user accounts)\n"
. "THIS WILL DELETE ALL DATA.\nContinue? (Y/N)" );
$reinstall = $this->cliInput();
if ( $reinstall !== 'Y' ) {
// Nothing left to do. Remove database.lock and abort the script
$this->getContext()->dbLock( false );
return;
}
$this->out( "Import user names and tokens from the old database after re-installing?\n"
. "(Note: password and seed cannot be restored due to incompatibility in the database.\n"
. ' Instead the auth token will be used as the the new password) (Y/N)' );
$reimportUsers = $this->cliInput();
// Drop all known TestSwarm tables in the database
// (except users, handled separately)
foreach ( array(
'run_client', // Removed in 1.0.0
'clients',
'run_useragent',
'useragents', // Removed in 1.0.0
'runs',
'jobs',
) as $dropTable ) {
$this->outRaw( "Dropping $dropTable table..." );
$exists = $db->tableExists( $dropTable );
if ( $exists ) {
$dropped = $db->query( 'DROP TABLE ' . $db->addIdentifierQuotes( $dropTable ) );
$this->out( ' ' . ($dropped ? 'OK' : 'FAILED' ) );
} else {
$this->out( 'SKIPPED (didn\'t exist)' );
}
}
// Handle users table (reimport or drop as well)
$userRows = array();
if ( $reimportUsers === 'Y' ) {
$this->out( 'Upgrading users table' );
$this->outRaw( 'Fetching current users...' );
$has_users = $db->tableExists( 'users' );
if ( !$has_users ) {
$this->out( 'SKIPPED (users table didn\'t exist)' );
} else {
$userRows = $db->getRows( 'SELECT * FROM users' );
$this->out( 'OK' );
}
}
$this->outRaw( 'Dropping users table...' );
$dropped = $db->query( 'DROP TABLE users' );
$this->out( ' ' . ($dropped ? 'OK' : 'FAILED') );
// Create new tables
$this->outRaw( 'Creating new tables... (this may take a few minutes)' );
global $swarmInstallDir;
$fullSchemaFile = "$swarmInstallDir/config/tables.sql";
if ( !is_readable( $fullSchemaFile ) ) {
$this->error( 'Can\'t read schema file' );
}
$fullSchemaSql = file_get_contents( $fullSchemaFile );
$executed = $db->batchQueryFromFile( $fullSchemaSql );
if ( !$executed ) {
$this->error( 'Creating new tables failed' );
}
$this->out( 'OK' );
if ( $reimportUsers === 'Y' ) {
$this->out( 'Re-importing ' . count( $userRows ) . ' users...' );
foreach ( $userRows as $userRow ) {
$this->outRaw( '- creating user "' . $userRow->name . '"... ' );
if ( empty( $userRow->password ) || empty( $userRow->seed ) || empty( $userRow->auth ) ) {
$this->out( 'SKIPPED: Not a project account but a swarm client.' );
continue;
}
try {
$signupAction = SignupAction::newFromContext( $this->getContext() );
// Password stored in the old database is a hash of the old seed (of type 'double'
// and the actual password. We can't create this user with the same password because
// sha1 is not supposed to be decodable.
// I tried overriding the created row after the creation with the old seed and password,
// but that didn't work because the old seed doesn't fit in the new seed field (of binary(40)).
// When inserted, mysql transforms it into something else and sha1(seed + password) will no
// longer match the hash. So instead create the new user with the auth token as password.
$signupAction->doCreateUser( $userRow->name, $userRow->auth );
$err = $signupAction->getError();
if ( !$err ) {
$this->outRaw( 'OK. Restoring auth token... ' );
$data = $signupAction->getData();
$updated = $db->query(str_queryf(
'UPDATE users
SET
auth = %s
WHERE id = %u',
$userRow->auth,
$data['userID']
));
$this->out( $updated ? 'OK.' : 'FAILED.' );
} else {
$this->out( "FAILED. SignupAction error. {$err['info']}" );
}
} catch ( Exception $e ) {
$this->out( "FAILED. Unexpected exception thrown while creating account. {$e->getMessage()}" );
}
}
} // End of users re-import
} // End of patch-new-ua-runresults.sql
/**
* 1.0.0-alpha (patch-users-projects-conversion.sql)
* users table removed, new projects table, various column changes.
*/
$has_users = $db->tableExists( 'users' );
$has_clients_user_id = $db->fieldInfo( 'clients', 'user_id' );
$has_jobs_user_id = $db->fieldInfo( 'jobs', 'user_id' );
$has_projects = $db->tableExists( 'projects' );
$has_clients_name = $db->fieldInfo( 'clients', 'name' );
$has_jobs_project_id = $db->fieldInfo( 'jobs', 'project_id' );
$has_clients_useragent_id = $db->fieldInfo( 'clients', 'useragent_id' );
if ( !$has_users && !$has_clients_user_id && !$has_jobs_user_id ) {
$this->out( '... users table already dropped' );
$this->out( '... clients.user_id already dropped' );
$this->out( '... jobs.user_id already dropped' );
} else {
// Verify that the entire database is in the 1.0.0-alpha2012 state,
// not just part of it.
foreach ( array(
'users table' => $has_users,
'clients.user_id' => $has_clients_user_id,
'jobs.user_id' => $has_jobs_user_id,
'projects table' => ! $has_projects,
'clients.name' => ! $has_clients_name,
'jobs.project_id' => ! $has_jobs_project_id,
'clients.useragent_id' => $has_clients_useragent_id,
) as $label => $isAsExpected)
if ( !$isAsExpected ) {
$this->unknownDatabaseState( $label . ' not found' );
return;
}
$this->out( 'Schema changes before users-projects-conversion migration...' );
$this->out( '... creating projects table' );
$db->query(
"CREATE TABLE `projects` (
`id` varchar(255) binary NOT NULL PRIMARY KEY,
`display_title` varchar(255) binary NOT NULL,
`site_url` blob NOT NULL default '',
`password` tinyblob NOT NULL,
`auth_token` tinyblob NOT NULL,
`updated` binary(14) NOT NULL,
`created` binary(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
);
$this->out( '... adding clients.name' );
$db->query(
"ALTER TABLE clients
ADD `name` varchar(255) binary NOT NULL AFTER `id`"
);
$this->out( '... adding jobs.project_id' );
$db->query(
"ALTER TABLE jobs
ADD `project_id` varchar(255) binary NOT NULL AFTER `name`"
);
$this->out( '... dropping constraint fk_clients_user_id' );
$db->query(
"ALTER TABLE clients
DROP FOREIGN KEY fk_clients_user_id"
);
$this->out( '... dropping constraint fk_jobs_user_id' );
$db->query(
"ALTER TABLE jobs
DROP FOREIGN KEY fk_jobs_user_id"
);
$this->out( '... dropping constraint fk_runs_job_id' );
$db->query(
"ALTER TABLE runs
DROP FOREIGN KEY fk_runs_job_id"
);
$this->out( '... dropping constraint fk_run_useragent_run_id' );
$db->query(
"ALTER TABLE run_useragent
DROP FOREIGN KEY fk_run_useragent_run_id"
);
$this->out( '... dropping constraint fk_runresults_client_id' );
$db->query(
"ALTER TABLE runresults
DROP FOREIGN KEY fk_runresults_client_id"
);
$this->out( '... dropping index idx_users_name' );
$db->query(
"ALTER TABLE users
DROP INDEX idx_users_name"
);
$this->out( '... dropping index idx_clients_user_useragent_updated' );
$db->query(
"ALTER TABLE clients
DROP INDEX idx_clients_user_useragent_updated"
);
$this->out( '... dropping index idx_jobs_user' );
$db->query(
"ALTER TABLE jobs
DROP INDEX idx_jobs_user"
);
$this->out( 'Migrating old content into new schema...' );
$this->out( '... fetching users table' );
$userRows = $db->getRows( 'SELECT * FROM users' ) ?: array();
$this->out( '... found ' . count( $userRows ) . ' users' );
foreach ( $userRows as $userRow ) {
$this->out( '... creating project "' . $userRow->name . '"' );
if ( !trim( $userRow->seed ) || !trim( $userRow->password ) || !trim( $userRow->auth ) ) {
// Client.php used to create rows in the users table with blanks
// in these "required" fields. MySQL expands the emptyness to the full
// 40-width of the column. Hence the trim().
$this->out( ' SKIPPED: Not a project account but a swarm client.' );
continue;
}
// Validate project id
if ( !LoginAction::isValidName( $userRow->name ) ) {
$this->out( ' SKIPPED: User name not a valid project id. Must match: ' . LoginAction::getNameValidationRegex() );
continue;
}
if ( !$db->getOne(str_queryf( 'SELECT 1 FROM jobs WHERE user_id=%u', $userRow->id )) ) {
$this->out( ' SKIPPED: Account has 0 jobs' );
continue;
}
$isInserted = $db->query(str_queryf(
'INSERT INTO projects
(id, display_title, site_url, password, auth_token, updated, created)
VALUES(%s, %s, %s, %s, %s, %s, %s);',
$userRow->name,
$userRow->name,
'',
LoginAction::generatePasswordHashForUserrow( $userRow ),
sha1( $userRow->auth ),
swarmdb_dateformat( SWARM_NOW ),
$userRow->created
));
if ( !$isInserted ) {
$this->out( ' FAILED: Failed to insert row into projects table.' );
continue;
}
$this->out( '... updating references for project "' . $userRow->name . '"' );
$isUpdated = $db->query(str_queryf(
'UPDATE clients
SET name=%s
WHERE user_id=%u',
$userRow->name,
$userRow->id
));
if ( !$isUpdated ) {
$this->out( ' FAILED: Failed to update rows in clients table.' );
continue;
}
$isUpdated = $db->query(str_queryf(
'UPDATE jobs
SET project_id=%s
WHERE user_id=%u',
$userRow->name,
$userRow->id
));
if ( !$isUpdated ) {
$this->out( ' FAILED: Failed to update rows in jobs table.' );
continue;
}
}
$this->out( 'Schema changes after users-projects-conversion migration...' );
$this->out( '... changing clients.useragent_id' );
$db->query(
"ALTER TABLE clients
CHANGE COLUMN `useragent_id` `useragent_id` varchar(255) NOT NULL"
);
$this->out( '... dropping clients.user_id' );
$db->query(
"ALTER TABLE clients
DROP COLUMN `user_id`"
);
$this->out( '... dropping jobs.user_id' );
$db->query(
"ALTER TABLE jobs
DROP COLUMN `user_id`"
);
$this->out( '... dropping users table' );
$db->query(
"DROP TABLE users"
);
$this->out( '... adding index idx_clients_name_ua_created' );
$db->query(
"ALTER TABLE clients
ADD INDEX idx_clients_name_ua_created (name, useragent_id, created);" );
$this->out( '... adding index idx_jobs_project_created' );
$db->query(
"ALTER TABLE jobs
ADD INDEX idx_jobs_project_created (project_id, created);" );
} // End of patch-users-projects-conversion.sql
$this->getContext()->dbLock( false );
$this->out( "Removed database.lock.\nNo more updates." );
}
protected function unknownDatabaseState( $error = '' ) {
if ( $error !== '' ) {
$error = "\n\nLast failed check before abort: $error";
}
$this->error( "\nThe database was found in a state not known in any version.\n"
. "This could be the result of a previous update run being aborted mid-update,\n"
. "in that case the automatic update script cannot help you.\n"
. "Please verify your local settings. Note that this is not an installer! $error" );
}
}
$script = DBUpdateScript::newFromContext( $swarmContext );
$script->run();