Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Trait that adds read-only slave connection capability
19
 *
20
 * @package    core
21
 * @category   dml
22
 * @copyright  2018 Srdjan Janković, Catalyst IT
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1441 ariadna 24
 * @deprecated Since Moodle 5.0. See MDL-71257.
25
 * @todo       Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 26
 */
1441 ariadna 27
#[\core\attribute\deprecated(
28
    replacement: moodle_read_replica_trait::class,
29
    since: '5.0',
30
    mdl: 'MDL-71257',
31
    reason: 'Renamed'
32
)]
1 efrain 33
 
34
/**
35
 * Trait to wrap connect() method of database driver classes that gives
36
 * ability to use read only slave instances for SELECT queries. For the
37
 * databases that support replication and read only connections to the slave.
38
 * If the slave connection is configured there will be two database handles
39
 * created, one for the master and another one for the slave. If there's no
40
 * slave specified everything uses master handle.
41
 *
42
 * Classes that use this trait need to rename existing connect() method to
43
 * raw_connect(). In addition, they need to provide get_db_handle() and
44
 * set_db_handle() methods, due to dbhandle attributes not being named
45
 * consistently across the database driver classes.
46
 *
47
 * Read only slave connection is configured in the $CFG->dboptions['readonly']
48
 * array.
49
 * - It supports multiple 'instance' entries, in case one is not accessible,
50
 *   but only one (first connectable) instance is used.
51
 * - 'latency' option: master -> slave sync latency in seconds (will probably
52
 *   be a fraction of a second). A table being written to is deemed fully synced
53
 *   after that period and suitable for slave read. Defaults to 1 sec.
54
 * - 'exclude_tables' option: a list of tables that never go to the slave for
55
 *   querying. The feature is meant to be used in emergency only, so the
56
 *   readonly feature can still be used in case there is a rogue query that
57
 *   does not go through the standard dml interface or some other unaccounted
58
 *   situation. It should not be used under normal circumstances, and its use
59
 *   indicates a problem in the system that needs addressig.
60
 *
61
 * Choice of the database handle is based on following:
62
 * - SQL_QUERY_INSERT, UPDATE and STRUCTURE record table from the query
63
 *   in the $written array and microtime() the event. For those queries master
64
 *   write handle is used.
65
 * - SQL_QUERY_AUX queries will always use the master write handle because they
66
 *   are used for transaction start/end, locking etc. In that respect, query_start() and
67
 *   query_end() *must not* be used during the connection phase.
68
 * - SQL_QUERY_AUX_READONLY queries will use the master write handle if in a transaction.
69
 * - SELECT queries will use the master write handle if:
70
 *   -- any of the tables involved is a temp table
71
 *   -- any of the tables involved is listed in the 'exclude_tables' option
72
 *   -- any of the tables involved is in the $written array:
73
 *      * current microtime() is compared to the write microrime, and if more than
74
 *        latency time has passed the slave handle is used
75
 *      * otherwise (not enough time passed) we choose the master write handle
76
 *   If none of the above conditions are met the slave instance is used.
77
 *
78
 * A 'latency' example:
79
 *  - we have set $CFG->dboptions['readonly']['latency'] to 0.2.
80
 *  - a SQL_QUERY_UPDATE to table tbl_x happens, and it is recorded in
81
 *    the $written array
82
 *  - 0.15 seconds later SQL_QUERY_SELECT with tbl_x is requested - the master
83
 *    connection is used
84
 *  - 0.10 seconds later (0.25 seconds after SQL_QUERY_UPDATE) another
85
 *    SQL_QUERY_SELECT with tbl_x is requested - this time more than 0.2 secs
86
 *    has gone and master -> slave sync is assumed, so the slave connection is
87
 *    used again
88
 */
89
 
90
trait moodle_read_slave_trait {
91
 
92
    /** @var resource master write database handle */
93
    protected $dbhwrite;
94
 
95
    /** @var resource slave read only database handle */
96
    protected $dbhreadonly;
97
 
98
    private $wantreadslave = false;
99
    private $readsslave = 0;
100
    private $slavelatency = 1;
101
    private $structurechange = false;
102
 
103
    private $written = []; // Track tables being written to.
104
    private $readexclude = []; // Tables to exclude from using dbhreadonly.
105
 
106
    // Store original params.
107
    private $pdbhost;
108
    private $pdbuser;
109
    private $pdbpass;
110
    private $pdbname;
111
    private $pprefix;
112
    private $pdboptions;
113
 
114
    /**
115
     * Gets db handle currently used with queries
116
     * @return resource
117
     */
118
    abstract protected function get_db_handle();
119
 
120
    /**
121
     * Sets db handle to be used with subsequent queries
122
     * @param resource $dbh
123
     * @return void
124
     */
125
    abstract protected function set_db_handle($dbh): void;
126
 
127
    /**
128
     * Connect to db
129
     * The real connection establisment, called from connect() and set_dbhwrite()
130
     * @param string $dbhost The database host.
131
     * @param string $dbuser The database username.
132
     * @param string $dbpass The database username's password.
133
     * @param string $dbname The name of the database being connected to.
134
     * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
135
     * @param array $dboptions driver specific options
136
     * @return bool true
137
     * @throws dml_connection_exception if error
138
     */
1441 ariadna 139
    abstract protected function raw_connect(string $dbhost, string $dbuser, string $dbpass, string $dbname, $prefix, ?array $dboptions = null): bool;
1 efrain 140
 
141
    /**
142
     * Connect to db
143
     * The connection parameters processor that sets up stage for master write and slave readonly handles.
144
     * Must be called before other methods.
145
     * @param string $dbhost The database host.
146
     * @param string $dbuser The database username.
147
     * @param string $dbpass The database username's password.
148
     * @param string $dbname The name of the database being connected to.
149
     * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
150
     * @param array $dboptions driver specific options
151
     * @return bool true
152
     * @throws dml_connection_exception if error
1441 ariadna 153
     * @deprecated Since Moodle 5.0. See MDL-71257.
154
     * @todo Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 155
     */
1441 ariadna 156
    #[\core\attribute\deprecated(
157
        replacement: 'moodle_read_replica_trait::connect',
158
        since: '5.0',
159
        mdl: 'MDL-71257',
160
        reason: 'Renamed trait'
161
    )]
162
    public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, ?array $dboptions = null) {
163
        \core\deprecation::emit_deprecation(__FUNCTION__);
1 efrain 164
        $this->pdbhost = $dbhost;
165
        $this->pdbuser = $dbuser;
166
        $this->pdbpass = $dbpass;
167
        $this->pdbname = $dbname;
168
        $this->pprefix = $prefix;
169
        $this->pdboptions = $dboptions;
170
 
1441 ariadna 171
        $logconnection = false;
1 efrain 172
        if ($dboptions) {
173
            if (isset($dboptions['readonly'])) {
174
                $this->wantreadslave = true;
175
                $dboptionsro = $dboptions['readonly'];
176
 
177
                if (isset($dboptionsro['connecttimeout'])) {
178
                    $dboptions['connecttimeout'] = $dboptionsro['connecttimeout'];
179
                } else if (!isset($dboptions['connecttimeout'])) {
180
                    $dboptions['connecttimeout'] = 2; // Default readonly connection timeout.
181
                }
182
                if (isset($dboptionsro['latency'])) {
183
                    $this->slavelatency = $dboptionsro['latency'];
184
                }
185
                if (isset($dboptionsro['exclude_tables'])) {
186
                    $this->readexclude = $dboptionsro['exclude_tables'];
187
                    if (!is_array($this->readexclude)) {
188
                        throw new configuration_exception('exclude_tables must be an array');
189
                    }
190
                }
191
                $dbport = isset($dboptions['dbport']) ? $dboptions['dbport'] : null;
192
 
193
                $slaves = $dboptionsro['instance'];
194
                if (!is_array($slaves) || !isset($slaves[0])) {
195
                    $slaves = [$slaves];
196
                }
197
 
198
                if (count($slaves) > 1) {
1441 ariadna 199
                    // Don't shuffle for unit tests as order is important for them to pass.
200
                    if (!PHPUNIT_TEST) {
201
                        // Randomise things a bit.
202
                        shuffle($slaves);
203
                    }
1 efrain 204
                }
205
 
206
                // Find first connectable readonly slave.
207
                $rodb = [];
208
                foreach ($slaves as $slave) {
209
                    if (!is_array($slave)) {
210
                        $slave = ['dbhost' => $slave];
211
                    }
212
                    foreach (['dbhost', 'dbuser', 'dbpass'] as $dbparam) {
213
                        $rodb[$dbparam] = isset($slave[$dbparam]) ? $slave[$dbparam] : $$dbparam;
214
                    }
215
                    $dboptions['dbport'] = isset($slave['dbport']) ? $slave['dbport'] : $dbport;
216
 
217
                    try {
218
                        $this->raw_connect($rodb['dbhost'], $rodb['dbuser'], $rodb['dbpass'], $dbname, $prefix, $dboptions);
219
                        $this->dbhreadonly = $this->get_db_handle();
1441 ariadna 220
                        if ($logconnection) {
221
                            debugging(
222
                                "Readonly db connection succeeded for host {$rodb['dbhost']}"
223
                            );
224
                        }
1 efrain 225
                        break;
1441 ariadna 226
                    } catch (dml_connection_exception $e) {
227
                        debugging(
228
                            "Readonly db connection failed for host {$rodb['dbhost']}: {$e->debuginfo}"
229
                        );
230
                        $logconnection = true;
1 efrain 231
                    }
232
                }
233
                // ... lock_db queries always go to master.
234
                // Since it is a lock and as such marshalls concurrent connections,
235
                // it is best to leave it out and avoid master/slave latency.
236
                $this->readexclude[] = 'lock_db';
237
                // ... and sessions.
238
                $this->readexclude[] = 'sessions';
239
            }
240
        }
241
        if (!$this->dbhreadonly) {
1441 ariadna 242
            try {
243
                $this->set_dbhwrite();
244
            } catch (dml_connection_exception $e) {
245
                debugging(
246
                    "Readwrite db connection failed for host {$this->pdbhost}: {$e->debuginfo}"
247
                );
248
                throw $e;
249
            }
250
            if ($logconnection) {
251
                debugging(
252
                    "Readwrite db connection succeeded for host {$this->pdbhost}"
253
                );
254
            }
1 efrain 255
        }
256
 
257
        return true;
258
    }
259
 
260
    /**
261
     * Set database handle to readwrite master
262
     * Will connect if required. Calls set_db_handle()
263
     * @return void
264
     */
265
    private function set_dbhwrite(): void {
266
        // Lazy connect to read/write master.
267
        if (!$this->dbhwrite) {
268
            $temptables = $this->temptables;
269
            $this->raw_connect($this->pdbhost, $this->pdbuser, $this->pdbpass, $this->pdbname, $this->pprefix, $this->pdboptions);
270
            if ($temptables) {
271
                $this->temptables = $temptables; // Restore temptables, so we don't get separate sets for rw and ro.
272
            }
273
            $this->dbhwrite = $this->get_db_handle();
274
        }
275
        $this->set_db_handle($this->dbhwrite);
276
    }
277
 
278
    /**
279
     * Returns whether we want to connect to slave database for read queries.
280
     * @return bool Want read only connection
1441 ariadna 281
     * @deprecated Since Moodle 5.0. See MDL-71257.
282
     * @todo Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 283
     */
1441 ariadna 284
    #[\core\attribute\deprecated(
285
        replacement: 'moodle_read_replica_trait::want_read_replica',
286
        since: '5.0',
287
        mdl: 'MDL-71257',
288
        reason: 'Renamed trait'
289
    )]
1 efrain 290
    public function want_read_slave(): bool {
1441 ariadna 291
        \core\deprecation::emit_deprecation(__FUNCTION__);
1 efrain 292
        return $this->wantreadslave;
293
    }
294
 
295
    /**
296
     * Returns the number of reads done by the read only database.
297
     * @return int Number of reads.
1441 ariadna 298
     * @deprecated Since Moodle 5.0. See MDL-71257.
299
     * @todo Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 300
     */
1441 ariadna 301
    #[\core\attribute\deprecated(
302
        replacement: 'moodle_read_replica_trait::perf_get_reads_replica',
303
        since: '5.0',
304
        mdl: 'MDL-71257',
305
        reason: 'Renamed trait'
306
    )]
1 efrain 307
    public function perf_get_reads_slave(): int {
1441 ariadna 308
        \core\deprecation::emit_deprecation(__FUNCTION__);
1 efrain 309
        return $this->readsslave;
310
    }
311
 
312
    /**
313
     * On DBs that support it, switch to transaction mode and begin a transaction
314
     * @return moodle_transaction
1441 ariadna 315
     * @deprecated Since Moodle 5.0. See MDL-71257.
316
     * @todo Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 317
     */
1441 ariadna 318
    #[\core\attribute\deprecated(
319
        replacement: 'moodle_read_replica_trait::start_delegated_transaction',
320
        since: '5.0',
321
        mdl: 'MDL-71257',
322
        reason: 'Renamed trait'
323
    )]
1 efrain 324
    public function start_delegated_transaction() {
1441 ariadna 325
        \core\deprecation::emit_deprecation(__FUNCTION__);
1 efrain 326
        $this->set_dbhwrite();
327
        return parent::start_delegated_transaction();
328
    }
329
 
330
    /**
331
     * Called before each db query.
332
     * @param string $sql
333
     * @param array|null $params An array of parameters.
334
     * @param int $type type of query
335
     * @param mixed $extrainfo driver specific extra information
336
     * @return void
337
     */
338
    protected function query_start($sql, ?array $params, $type, $extrainfo = null) {
339
        parent::query_start($sql, $params, $type, $extrainfo);
340
        $this->select_db_handle($type, $sql);
341
    }
342
 
343
    /**
344
     * This should be called immediately after each db query. It does a clean up of resources.
345
     *
346
     * @param mixed $result The db specific result obtained from running a query.
347
     * @return void
348
     */
349
    protected function query_end($result) {
350
        if ($this->written) {
351
            // Adjust the written time.
352
            array_walk($this->written, function (&$val) {
353
                if ($val === true) {
354
                    $val = microtime(true);
355
                }
356
            });
357
        }
358
 
359
        parent::query_end($result);
360
    }
361
 
362
    /**
363
     * Select appropriate db handle - readwrite or readonly
364
     * @param int $type type of query
365
     * @param string $sql
366
     * @return void
367
     */
368
    protected function select_db_handle(int $type, string $sql): void {
369
        if ($this->dbhreadonly && $this->can_use_readonly($type, $sql)) {
370
            $this->readsslave++;
371
            $this->set_db_handle($this->dbhreadonly);
372
            return;
373
        }
374
        $this->set_dbhwrite();
375
    }
376
 
377
    /**
378
     * Check if The query qualifies for readonly connection execution
379
     * Logging queries are exempt, those are write operations that circumvent
380
     * standard query_start/query_end paths.
381
     * @param int $type type of query
382
     * @param string $sql
383
     * @return bool
384
     */
385
    protected function can_use_readonly(int $type, string $sql): bool {
386
        if ($this->loggingquery) {
387
            return false;
388
        }
389
 
390
        if (during_initial_install()) {
391
            return false;
392
        }
393
 
394
        // Transactions are done as AUX, we cannot play with that.
395
        switch ($type) {
396
            case SQL_QUERY_AUX_READONLY:
397
                // SQL_QUERY_AUX_READONLY may read the structure data.
398
                // We don't have a way to reliably determine whether it is safe to go to readonly if the structure has changed.
399
                return !$this->structurechange;
400
            case SQL_QUERY_SELECT:
401
                if ($this->transactions) {
402
                    return false;
403
                }
404
 
405
                $now = null;
406
                foreach ($this->table_names($sql) as $tablename) {
407
                    if (in_array($tablename, $this->readexclude)) {
408
                        return false;
409
                    }
410
 
411
                    if ($this->temptables && $this->temptables->is_temptable($tablename)) {
412
                        return false;
413
                    }
414
 
415
                    if (isset($this->written[$tablename])) {
416
                        $now = $now ?: microtime(true);
417
 
418
                        if ($now - $this->written[$tablename] < $this->slavelatency) {
419
                            return false;
420
                        }
421
                        unset($this->written[$tablename]);
422
                    }
423
                }
424
 
425
                return true;
426
            case SQL_QUERY_INSERT:
427
            case SQL_QUERY_UPDATE:
428
                foreach ($this->table_names($sql) as $tablename) {
429
                    $this->written[$tablename] = true;
430
                }
431
                return false;
432
            case SQL_QUERY_STRUCTURE:
433
                $this->structurechange = true;
434
                foreach ($this->table_names($sql) as $tablename) {
435
                    if (!in_array($tablename, $this->readexclude)) {
436
                        $this->readexclude[] = $tablename;
437
                    }
438
                }
439
                return false;
440
        }
441
        return false;
442
    }
443
 
444
    /**
445
     * Indicates delegated transaction finished successfully.
446
     * Set written times after outermost transaction finished
447
     * @param moodle_transaction $transaction The transaction to commit
448
     * @return void
449
     * @throws dml_transaction_exception Creates and throws transaction related exceptions.
1441 ariadna 450
     * @deprecated Since Moodle 5.0. See MDL-71257.
451
     * @todo Final deprecation in Moodle 6.0. See MDL-83171.
1 efrain 452
     */
1441 ariadna 453
    #[\core\attribute\deprecated(
454
        replacement: 'moodle_read_replica_trait::commit_delegated_transaction',
455
        since: '5.0',
456
        mdl: 'MDL-71257',
457
        reason: 'Renamed trait'
458
    )]
1 efrain 459
    public function commit_delegated_transaction(moodle_transaction $transaction) {
1441 ariadna 460
        \core\deprecation::emit_deprecation(__FUNCTION__);
1 efrain 461
        if ($this->written) {
462
            // Adjust the written time.
463
            $now = microtime(true);
464
            foreach ($this->written as $tablename => $when) {
465
                $this->written[$tablename] = $now;
466
            }
467
        }
468
 
469
        parent::commit_delegated_transaction($transaction);
470
    }
471
 
472
    /**
473
     * Parse table names from query
474
     * @param string $sql
475
     * @return array
476
     */
477
    protected function table_names(string $sql): array {
478
        preg_match_all('/\b'.$this->prefix.'([a-z][A-Za-z0-9_]*)/', $sql, $match);
479
        return $match[1];
480
    }
481
}