Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 102
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
MysqlMaintenance
0.00% covered (danger)
0.00%
0 / 99
0.00% covered (danger)
0.00%
0 / 3
756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
240
 runMysql
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
132
1<?php
2/**
3 * Execute the MySQL client binary, connecting to the wiki's DB.
4 * Note that this will not do table prefixing or variable substitution.
5 * To safely run schema patches, use sql.php.
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup Maintenance
24 */
25
26use MediaWiki\Shell\Shell;
27use Wikimedia\IPUtils;
28
29require_once __DIR__ . '/Maintenance.php';
30
31/**
32 * @ingroup Maintenance
33 */
34class MysqlMaintenance extends Maintenance {
35    public function __construct() {
36        parent::__construct();
37        $this->addDescription( "Execute the MySQL client binary. " .
38            "Non-option arguments will be passed through to mysql." );
39        $this->addOption( 'write', 'Connect to the primary database', false, false );
40        $this->addOption( 'group', 'Specify query group', false, true );
41        $this->addOption( 'host', 'Connect to a known MySQL server', false, true );
42        $this->addOption( 'raw-host',
43            'Connect directly to a specific MySQL server, even if not known to MediaWiki '
44                . 'via wgLBFactoryConf (e.g. parser cache or depooled host). '
45                . 'Credentails will be chosen based on --cluster and --wikidb.',
46            false,
47            true
48        );
49        $this->addOption( 'list-hosts', 'List the available DB hosts', false, false );
50        $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
51        $this->addOption( 'wikidb',
52            'The database wiki ID to use if not the current one',
53            false,
54            true
55        );
56
57        // Fake argument for help message
58        $this->addArg( '-- mysql_option ...', 'Options to pass to mysql', false );
59    }
60
61    public function execute() {
62        $dbName = $this->getOption( 'wikidb', false );
63        $lbf = $this->getServiceContainer()->getDBLoadBalancerFactory();
64
65        // Pick LB
66        if ( $this->hasOption( 'cluster' ) ) {
67            try {
68                $lb = $lbf->getExternalLB( $this->getOption( 'cluster' ) );
69            } catch ( InvalidArgumentException $e ) {
70                $this->fatalError( 'Error: invalid cluster' );
71            }
72        } else {
73            $lb = $lbf->getMainLB( $dbName );
74        }
75
76        // List hosts, or pick host
77        if ( $this->hasOption( 'list-hosts' ) ) {
78            $serverCount = $lb->getServerCount();
79            for ( $index = 0; $index < $serverCount; ++$index ) {
80                echo $lb->getServerName( $index ) . "\n";
81            }
82            return;
83        }
84        if ( $this->hasOption( 'host' ) ) {
85            $host = $this->getOption( 'host' );
86            $serverCount = $lb->getServerCount();
87            for ( $index = 0; $index < $serverCount; ++$index ) {
88                if ( $lb->getServerName( $index ) === $host ) {
89                    break;
90                }
91            }
92            if ( $index >= $serverCount ) {
93                $this->fatalError( "Error: Host not configured: \"$host\"" );
94            }
95        } elseif ( $this->hasOption( 'write' ) ) {
96            $index = $lb->getWriterIndex();
97        } else {
98            $group = $this->getOption( 'group', false );
99            $index = $lb->getReaderIndex( $group );
100            if ( $index === false && $group ) {
101                // retry without the group; it may not exist
102                $index = $lb->getReaderIndex( false );
103            }
104            if ( $index === false ) {
105                $this->fatalError( 'Error: unable to get reader index' );
106            }
107        }
108        if ( $lb->getServerType( $index ) !== 'mysql' ) {
109            $this->fatalError( 'Error: this script only works with MySQL/MariaDB' );
110        }
111
112        $serverInfo = $lb->getServerInfo( $index );
113        // Override host. This uses the server info of the host determined
114        // by the other options for the purposes of user/password.
115        if ( $this->hasOption( 'raw-host' ) ) {
116            $host = $this->getOption( 'raw-host' );
117            $serverInfo = [ 'host' => $host ] + $serverInfo;
118        }
119
120        $this->runMysql( $serverInfo, $dbName );
121    }
122
123    /**
124     * Run the mysql client for the given server info
125     *
126     * @param array $info
127     * @param string|false $dbName The DB name, or false to use the main wiki DB
128     */
129    private function runMysql( $info, $dbName ) {
130        // Write the password to an option file to avoid disclosing it to other
131        // processes running on the system
132        $tmpFile = TempFSFile::factory( 'mw-mysql', 'ini' );
133        chmod( $tmpFile->getPath(), 0600 );
134        file_put_contents( $tmpFile->getPath(), "[client]\npassword={$info['password']}\n" );
135
136        // stdin/stdout need to be the actual file descriptors rather than
137        // PHP's pipe wrappers so that mysql can use them as an interactive
138        // terminal.
139        $desc = [
140            0 => STDIN,
141            1 => STDOUT,
142            2 => STDERR,
143        ];
144
145        // Split host and port as in DatabaseMySQL::mysqlConnect()
146        $realServer = $info['host'];
147        $hostAndPort = IPUtils::splitHostAndPort( $realServer );
148        $socket = false;
149        $port = false;
150        if ( $hostAndPort ) {
151            $realServer = $hostAndPort[0];
152            if ( $hostAndPort[1] ) {
153                $port = $hostAndPort[1];
154            }
155        } elseif ( substr_count( $realServer, ':' ) == 1 ) {
156            // If we have a colon and something that's not a port number
157            // inside the hostname, assume it's the socket location
158            [ $realServer, $socket ] = explode( ':', $realServer, 2 );
159        }
160
161        if ( $dbName === false ) {
162            $dbName = $info['dbname'];
163        }
164
165        $args = [
166            'mysql',
167            "--defaults-extra-file={$tmpFile->getPath()}",
168            "--user={$info['user']}",
169            "--database={$dbName}",
170        ];
171        if ( $socket !== false ) {
172            $args[] = "--socket={$socket}";
173        } else {
174            $args[] = "--host={$realServer}";
175        }
176        if ( $port !== false ) {
177            $args[] = "--port={$port}";
178        }
179
180        $args = array_merge( $args, $this->getArgs() );
181
182        // Ignore SIGINT if possible, otherwise the wrapper terminates when the user presses
183        // ctrl-C to kill a query.
184        if ( function_exists( 'pcntl_signal' ) ) {
185            pcntl_signal( SIGINT, SIG_IGN );
186        }
187
188        $pipes = [];
189        $proc = proc_open( Shell::escape( $args ), $desc, $pipes );
190        if ( $proc === false ) {
191            $this->fatalError( 'Unable to execute mysql' );
192        }
193
194        $ret = proc_close( $proc );
195        if ( $ret === -1 ) {
196            $this->fatalError( 'proc_close() returned -1' );
197        } elseif ( $ret ) {
198            $this->fatalError( 'Failed.', $ret );
199        }
200    }
201}
202
203$maintClass = MysqlMaintenance::class;
204require_once RUN_MAINTENANCE_IF_MAIN;