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