Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 99
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\Maintenance\Maintenance;
27use MediaWiki\Shell\Shell;
28use Wikimedia\FileBackend\FSFile\TempFSFile;
29use Wikimedia\IPUtils;
30use Wikimedia\Rdbms\ServerInfo;
31
32// @codeCoverageIgnoreStart
33require_once __DIR__ . '/Maintenance.php';
34// @codeCoverageIgnoreEnd
35
36/**
37 * @ingroup Maintenance
38 */
39class MysqlMaintenance extends Maintenance {
40    public function __construct() {
41        parent::__construct();
42        $this->addDescription( "Execute the MySQL client binary. " .
43            "Non-option arguments will be passed through to mysql." );
44        $this->addOption( 'write', 'Connect to the primary database', false, false );
45        $this->addOption( 'group', 'Specify query group', false, true );
46        $this->addOption( 'host', 'Connect to a known MySQL server', false, true );
47        $this->addOption( 'raw-host',
48            'Connect directly to a specific MySQL server, even if not known to MediaWiki '
49                . 'via wgLBFactoryConf (e.g. parser cache or depooled host). '
50                . 'Credentails will be chosen based on --cluster and --wikidb.',
51            false,
52            true
53        );
54        $this->addOption( 'list-hosts', 'List the available DB hosts', false, false );
55        $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
56        $this->addOption( 'wikidb',
57            'The database wiki ID to use if not the current one',
58            false,
59            true
60        );
61
62        // Fake argument for help message
63        $this->addArg( '-- mysql_option ...', 'Options to pass to mysql', false );
64    }
65
66    public function execute() {
67        $dbName = $this->getOption( 'wikidb', false );
68        $lbf = $this->getServiceContainer()->getDBLoadBalancerFactory();
69
70        // Pick LB
71        if ( $this->hasOption( 'cluster' ) ) {
72            try {
73                $lb = $lbf->getExternalLB( $this->getOption( 'cluster' ) );
74            } catch ( InvalidArgumentException $e ) {
75                $this->fatalError( 'Error: invalid cluster' );
76            }
77        } else {
78            $lb = $lbf->getMainLB( $dbName );
79        }
80
81        // List hosts, or pick host
82        if ( $this->hasOption( 'list-hosts' ) ) {
83            $serverCount = $lb->getServerCount();
84            for ( $index = 0; $index < $serverCount; ++$index ) {
85                echo $lb->getServerName( $index ) . "\n";
86            }
87            return;
88        }
89        if ( $this->hasOption( 'host' ) ) {
90            $host = $this->getOption( 'host' );
91            $serverCount = $lb->getServerCount();
92            for ( $index = 0; $index < $serverCount; ++$index ) {
93                if ( $lb->getServerName( $index ) === $host ) {
94                    break;
95                }
96            }
97            if ( $index >= $serverCount ) {
98                $this->fatalError( "Error: Host not configured: \"$host\"" );
99            }
100        } elseif ( $this->hasOption( 'write' ) ) {
101            $index = ServerInfo::WRITER_INDEX;
102        } else {
103            $group = $this->getOption( 'group', false );
104            $index = $lb->getReaderIndex( $group );
105            if ( $index === false && $group ) {
106                // retry without the group; it may not exist
107                $index = $lb->getReaderIndex( false );
108            }
109            if ( $index === false ) {
110                $this->fatalError( 'Error: unable to get reader index' );
111            }
112        }
113        if ( $lb->getServerType( $index ) !== 'mysql' ) {
114            $this->fatalError( 'Error: this script only works with MySQL/MariaDB' );
115        }
116
117        $serverInfo = $lb->getServerInfo( $index );
118        // Override host. This uses the server info of the host determined
119        // by the other options for the purposes of user/password.
120        if ( $this->hasOption( 'raw-host' ) ) {
121            $host = $this->getOption( 'raw-host' );
122            $serverInfo = [ 'host' => $host ] + $serverInfo;
123        }
124
125        $this->runMysql( $serverInfo, $dbName );
126    }
127
128    /**
129     * Run the mysql client for the given server info
130     *
131     * @param array $info
132     * @param string|false $dbName The DB name, or false to use the main wiki DB
133     */
134    private function runMysql( $info, $dbName ) {
135        // Write the password to an option file to avoid disclosing it to other
136        // processes running on the system
137        $tmpFile = TempFSFile::factory( 'mw-mysql', 'ini' );
138        chmod( $tmpFile->getPath(), 0600 );
139        file_put_contents( $tmpFile->getPath(), "[client]\npassword={$info['password']}\n" );
140
141        // stdin/stdout need to be the actual file descriptors rather than
142        // PHP's pipe wrappers so that mysql can use them as an interactive
143        // terminal.
144        $desc = [
145            0 => STDIN,
146            1 => STDOUT,
147            2 => STDERR,
148        ];
149
150        // Split host and port as in DatabaseMySQL::mysqlConnect()
151        $realServer = $info['host'];
152        $hostAndPort = IPUtils::splitHostAndPort( $realServer );
153        $socket = false;
154        $port = false;
155        if ( $hostAndPort ) {
156            $realServer = $hostAndPort[0];
157            if ( $hostAndPort[1] ) {
158                $port = $hostAndPort[1];
159            }
160        } elseif ( substr_count( $realServer, ':' ) == 1 ) {
161            // If we have a colon and something that's not a port number
162            // inside the hostname, assume it's the socket location
163            [ $realServer, $socket ] = explode( ':', $realServer, 2 );
164        }
165
166        if ( $dbName === false ) {
167            $dbName = $info['dbname'];
168        }
169
170        $args = [
171            'mysql',
172            "--defaults-extra-file={$tmpFile->getPath()}",
173            "--user={$info['user']}",
174            "--database={$dbName}",
175        ];
176        if ( $socket !== false ) {
177            $args[] = "--socket={$socket}";
178        } else {
179            $args[] = "--host={$realServer}";
180        }
181        if ( $port !== false ) {
182            $args[] = "--port={$port}";
183        }
184
185        $args = array_merge( $args, $this->getArgs() );
186
187        // Ignore SIGINT if possible, otherwise the wrapper terminates when the user presses
188        // ctrl-C to kill a query.
189        if ( function_exists( 'pcntl_signal' ) ) {
190            pcntl_signal( SIGINT, SIG_IGN );
191        }
192
193        $pipes = [];
194        $proc = proc_open( Shell::escape( $args ), $desc, $pipes );
195        if ( $proc === false ) {
196            $this->fatalError( 'Unable to execute mysql' );
197        }
198
199        $ret = proc_close( $proc );
200        if ( $ret === -1 ) {
201            $this->fatalError( 'proc_close() returned -1' );
202        } elseif ( $ret ) {
203            $this->fatalError( 'Failed.', $ret );
204        }
205    }
206}
207
208// @codeCoverageIgnoreStart
209$maintClass = MysqlMaintenance::class;
210require_once RUN_MAINTENANCE_IF_MAIN;
211// @codeCoverageIgnoreEnd