feature: support non-standard unix socket (#5724)

* Add support for custom MySQL unix-socket

* NULL must be lowercase!

* Naive edit of html/install.php

* fixup

* Refactor dbConnect
Use it everywhere

* $config needs to be global
Don't need to set $database_link

* small cleanups
This commit is contained in:
Tony Murray 2017-04-06 16:02:37 -05:00 committed by Neil Lathwood
parent 66d9d54f73
commit b1a414e785
15 changed files with 196 additions and 129 deletions

View File

@ -0,0 +1,31 @@
<?php
/**
* DatabaseConnectException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2017 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class DatabaseConnectException extends \Exception
{
}

View File

@ -20,6 +20,8 @@
namespace LibreNMS;
use LibreNMS\Exceptions\DatabaseConnectException;
class IRCBot
{
@ -365,7 +367,7 @@ class IRCBot
}//end getUser()
private function connect($try)
private function connect($try = 0)
{
if ($try > $this->max_retry) {
$this->log('Failed too many connection attempts, aborting');
@ -437,15 +439,21 @@ class IRCBot
private function chkdb()
{
if (!is_resource($this->sql)) {
if (($this->sql = mysqli_connect($this->config['db_host'], $this->config['db_user'], $this->config['db_pass'], null, $this->config['db_port'])) != false && mysqli_select_db($this->sql, $this->config['db_name'])) {
return true;
} else {
$this->log('Cannot connect to MySQL');
try {
$this->sql = dbConnect(
$this->config['db_host'],
$this->config['db_user'],
$this->config['db_pass'],
$this->config['db_name'],
$this->config['db_port'],
$this->config['db_socket']
);
} catch (DatabaseConnectException $e) {
$this->log('Cannot connect to MySQL: ' . $e->getMessage());
return die();
}
} else {
return true;
}
return true;
}//end chkdb()

View File

@ -1,10 +1,13 @@
#!/usr/bin/env php
<?php
// MYSQL Check - FIXME
// 1 UNKNOWN
$config['db_port'] = null;
include 'config.php';
if (!isset($init_modules)) {
$init_modules = array();
require __DIR__ . '/includes/init.php';
$options = getopt('d');
$debug = isset($options['d']);
}
if (!isset($sql_file)) {
$sql_file = 'build.sql';
@ -12,45 +15,35 @@ if (!isset($sql_file)) {
$sql_fh = fopen($sql_file, 'r');
if ($sql_fh === false) {
echo 'ERROR: Cannot open SQL build script '.$sql_file."\n";
echo 'ERROR: Cannot open SQL build script '.$sql_file.PHP_EOL;
exit(1);
}
$database_link = mysqli_connect('p:'.$config['db_host'], $config['db_user'], $config['db_pass'], null, $config['db_port']);
if ($database_link === false) {
echo 'ERROR: Cannot connect to database: '.mysqli_error($database_link)."\n";
exit(1);
}
// only import build.sql to an empty database
$tables = dbFetchRows("SHOW TABLES FROM {$config['db_name']}");
if (empty($tables)) {
$limit = 0;
$select = mysqli_select_db($database_link, $config['db_name']);
mysqli_query($database_link, "SET NAMES 'utf8'");
mysqli_query($database_link, "SET CHARACTER SET 'utf8'");
mysqli_query($database_link, "SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
if ($select === false) {
echo 'ERROR: Cannot select database: '.mysqli_error($database_link)."\n";
exit(1);
}
$limit = 0;
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if (isset($_SESSION['stage'])) {
$limit++;
if (isset($_SESSION['offset']) && $limit < $_REQUEST['offset']) {
continue;
} elseif (time()-$_SESSION['last'] > 45) {
$_SESSION['offset'] = $limit;
$GLOBALS['refresh'] = '<b>Installing, please wait..</b><sub>'.date('r').'</sub><script>window.location.href = "install.php?offset='.$limit.'";</script>';
return;
} else {
echo 'Step #'.$limit.' ...'.PHP_EOL;
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if (isset($_SESSION['stage'])) {
$limit++;
if (isset($_SESSION['offset']) && $limit < $_REQUEST['offset']) {
continue;
} elseif (time()-$_SESSION['last'] > 45) {
$_SESSION['offset'] = $limit;
$GLOBALS['refresh'] = '<b>Installing, please wait..</b><sub>'.date('r').'</sub><script>window.location.href = "install.php?offset='.$limit.'";</script>';
return;
} else {
echo 'Step #'.$limit.' ...'.PHP_EOL;
}
}
}
if (!empty($line)) {
$creation = mysqli_query($database_link, $line);
if (!$creation) {
echo 'WARNING: Cannot execute query ('.$line.'): '.mysqli_error($database_link)."\n";
if (!empty($line)) {
$creation = dbQuery($line);
if (!$creation) {
echo 'WARNING: Cannot execute query ('.$line.'): '.mysqli_error($database_link)."\n";
}
}
}
}

View File

@ -92,6 +92,9 @@ db_port = int(config['db_port'])
if config['db_host'][:5].lower() == 'unix:':
db_server = config['db_host']
db_port = 0
elif config['db_socket']:
db_server = config['db_socket']
db_port = 0
else:
db_server = config['db_host']

View File

@ -32,6 +32,13 @@ $config['db_pass'] = '';
$config['db_name'] = '';
```
If you use a unix socket, you can specify it with these options:
```php
$config['db_host'] = NULL;
$config['db_port'] = NULL;
$config['db_socket'] = '/run/mysqld/mysqld.sock';
```
### Programs
A lot of these are self explanatory so no further information may be provided. Any extensions that have dedicated

View File

@ -29,11 +29,20 @@ $dbuser = @$_POST['dbuser'] ?: 'librenms';
$dbpass = @$_POST['dbpass'] ?: '';
$dbname = @$_POST['dbname'] ?: 'librenms';
$dbport = @$_POST['dbport'] ?: 3306;
$dbsocket = @$_POST['dbsocket'] ?: '';
$config['db_host']=$dbhost;
$config['db_user']=$dbuser;
$config['db_pass']=$dbpass;
$config['db_name']=$dbname;
$config['db_port']=$dbport;
$config['db_socket']=$dbsocket;
if (!empty($config['db_socket'])) {
$config['db_host'] = '';
$config['db_port'] = null;
} else {
$config['db_socket'] = null;
}
$add_user = @$_POST['add_user'] ?: '';
$add_pass = @$_POST['add_pass'] ?: '';
@ -42,18 +51,15 @@ $add_email = @$_POST['add_email'] ?: '';
// Check we can connect to MySQL DB, if not, back to stage 1 :)
if ($stage > 1) {
$database_link = mysqli_connect('p:'.$dbhost, $dbuser, $dbpass, $dbname, $dbport);
dbQuery("SET NAMES 'utf8'");
dbQuery("SET CHARACTER SET 'utf8'");
dbQuery("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
if (mysqli_connect_error()) {
$stage = 1;
$msg = "Couldn't connect to the database, please check your details<br /> " . mysqli_connect_error();
} elseif ($stage == 2) {
if ($_SESSION['build-ok'] == true) {
$stage = 3;
$msg = "It appears that the database is already setup so have moved onto stage $stage";
try {
dbConnect();
if ($stage == 2 && $_SESSION['build-ok'] == true) {
$stage = 3;
$msg = "It appears that the database is already setup so have moved onto stage $stage";
}
} catch (\LibreNMS\Exceptions\DatabaseConnectException $e) {
$stage = 1;
$msg = "Couldn't connect to the database, please check your details<br /> " . $e->getMessage();
}
$_SESSION['stage'] = $stage;
}
@ -255,13 +261,19 @@ if ($ext_loaded == 'no') {
<div class="form-group">
<label for="dbhost" class="col-sm-4" control-label">DB Host: </label>
<div class="col-sm-8">
<input type="text" class="form-control" name="dbhost" id="dbhost" value="<?php echo $dbhost; ?>">
<input type="text" class="form-control" name="dbhost" id="dbhost" value="<?php echo $dbhost; ?>" placeholder="Leave empty if using Unix-Socket">
</div>
</div>
<div class="form-group">
<label for="dbport" class="col-sm-4" control-label">DB Port: </label>
<div class="col-sm-8">
<input type="text" class="form-control" name="dbport" id="dbport" value="<?php echo $dbport; ?>">
<input type="text" class="form-control" name="dbport" id="dbport" value="<?php echo $dbport; ?>" placeholder="Leave empty if using Unix-Socket">
</div>
</div>
<div class="form-group">
<label for="dbsocket" class="col-sm-4" control-label">DB Unix-Socket: </label>
<div class="col-sm-8">
<input type="text" class="form-control" name="dbsocket" id="dbsocket" value="<?php echo $dbsocket; ?>" placeholder="Leave empty if using Host">
</div>
</div>
<div class="form-group">
@ -304,6 +316,7 @@ if ($ext_loaded == 'no') {
$config['db_pass'] = $dbpass;
$config['db_name'] = $dbname;
$config['db_port'] = $dbport;
$config['db_socket'] = $dbsocket;
$sql_file = '../build.sql';
$_SESSION['last'] = time();
ob_end_flush();
@ -335,6 +348,7 @@ if ($_SESSION['offset'] < 100 && $_REQUEST['offset'] < 94) {
<input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>">
<input type="hidden" name="dbname" value="<?php echo $dbname; ?>">
<input type="hidden" name="dbport" value="<?php echo $dbport; ?>">
<input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>">
<button type="submit" class="btn btn-success">Goto Add User</button>
</form>
</div>
@ -360,6 +374,7 @@ $config_file = <<<"EOD"
\$config\['db_user'\] = '$dbuser';
\$config\['db_pass'\] = '$dbpass';
\$config\['db_name'\] = '$dbname';
\$config\['db_socket'\] = '$dbsocket';
\$config\['db'\]\['extension'\] = "mysqli";// mysql or mysqli
// This is the user LibreNMS will run as
@ -421,6 +436,7 @@ if (!file_exists("../config.php")) {
<input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>">
<input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>">
<input type="hidden" name="dbname" value="<?php echo $dbname; ?>">
<input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>">
<button type="submit" class="btn btn-success">Finish install</button>
</form>
<?php
@ -443,6 +459,7 @@ if (!file_exists("../config.php")) {
<input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>">
<input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>">
<input type="hidden" name="dbname" value="<?php echo $dbname; ?>">
<input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>">
<div class="form-group">
<label for="add_user" class="col-sm-4 control-label">Username</label>
<div class="col-sm-8">
@ -498,6 +515,7 @@ if (auth_usermanagement()) {
<input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>">
<input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>">
<input type="hidden" name="dbname" value="<?php echo $dbname; ?>">
<input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>">
<button type="submit" class="btn btn-success" <?php if ($proceed == "1") {
echo "disabled='disabled'";
} ?>>Generate Config</button>

View File

@ -1,51 +0,0 @@
<?php
if (!isset($sql_file)) {
$sql_file = 'build.sql';
}
$sql_fh = fopen($sql_file, 'r');
if ($sql_fh === false) {
echo 'ERROR: Cannot open SQL build script '.$sql_file."\n";
exit(1);
}
$database_link = mysqli_connect('p:'.$config['db_host'], $config['db_user'], $config['db_pass']);
if ($database_link === false) {
echo 'ERROR: Cannot connect to database: '.mysqli_error($database_link)."\n";
exit(1);
}
$select = mysqli_select_db($database_link, $config['db_name']);
if ($select === false) {
echo 'ERROR: Cannot select database: '.mysqli_error($database_link)."\n";
exit(1);
}
$limit = 0;
while (!feof($sql_fh)) {
$line = fgetss($sql_fh);
if (isset($_SESSION['stage'])) {
$limit++;
if (isset($_SESSION['offset']) && $limit < $_REQUEST['offset']) {
continue;
} elseif (time()-$_SESSION['last'] > 45) {
$_SESSION['offset'] = $limit;
$GLOBALS['refresh'] = '<b>Installing, please wait..</b><sub>'.date('r').'</sub><script>window.location.href = "install.php?offset='.$limit.'";</script>';
return;
} else {
echo 'Step #'.$limit.' ...'.PHP_EOL;
}
}
if (!empty($line)) {
$creation = mysqli_query($database_link, $line);
if (!$creation) {
echo 'WARNING: Cannot execute query ('.$line.'): '.mysqli_error($database_link)."\n";
}
}
}
fclose($sql_fh);
require 'includes/sql-schema/update.php';

View File

@ -17,6 +17,58 @@
* 3. Oh, and dbFetchAll() is now dbFetchRows()
*/
use LibreNMS\Exceptions\DatabaseConnectException;
/**
* Connect to the database.
* Will use global $config variables if they are not sent: db_host, db_user, db_pass, db_name, db_port, db_socket
*
* @param string $host
* @param string $user
* @param string $password
* @param string $database
* @param string $port
* @param string $socket
* @return mysqli
* @throws DatabaseConnectException
*/
function dbConnect($host = null, $user = '', $password = '', $database = '', $port = null, $socket = null)
{
global $config, $database_link;
$host = empty($host) ? $config['db_host'] : $host;
$user = empty($user) ? $config['db_user'] : $user;
$password = empty($password) ? $config['db_pass'] : $password;
$database = empty($database) ? $config['db_name'] : $database;
$port = empty($port) ? $config['db_port'] : $port;
$socket = empty($socket) ? $config['db_socket'] : $socket;
$database_link = mysqli_connect('p:' . $host, $user, $password, null, $port, $socket);
if ($database_link === false) {
$error = mysqli_connect_error();
if ($error == 'No such file or directory') {
$error = 'Could not connect to ' . $host;
}
throw new DatabaseConnectException($error);
}
$database_db = mysqli_select_db($database_link, $config['db_name']);
if (!$database_db) {
$db_create_sql = "CREATE DATABASE " . $config['db_name'] . " CHARACTER SET utf8 COLLATE utf8_unicode_ci";
mysqli_query($database_link, $db_create_sql);
$database_db = mysqli_select_db($database_link, $config['db_name']);
}
if (!$database_db) {
throw new DatabaseConnectException("Could not select database: $database. " . mysqli_error($database_link));
}
dbQuery("SET NAMES 'utf8'");
dbQuery("SET CHARACTER SET 'utf8'");
dbQuery("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
return $database_link;
}
/*
* Performs a query using the given string.
* Used by the other _query functions.

View File

@ -36,6 +36,7 @@ $config['mysql_log_level'] = 'ERROR';
//MySQL port
$config['db_port'] = 3306;
$config['db_socket'] = null;
// What is my own hostname (used to identify this host in its own database)
$config['own_hostname'] = 'localhost';

View File

@ -27,6 +27,8 @@
* @param array $modules Which modules to initialize
*/
global $config;
$install_dir = realpath(__DIR__ . '/..');
$config['install_dir'] = $install_dir;
chdir($install_dir);
@ -103,20 +105,16 @@ if ($config['memcached']['enable'] === true) {
if (!module_selected('nodb', $init_modules)) {
// Connect to database
$database_link = mysqli_connect('p:' . $config['db_host'], $config['db_user'], $config['db_pass'], null, $config['db_port']);
if (!$database_link) {
echo '<h2>MySQL Error</h2>';
echo mysqli_connect_error();
die;
try {
dbConnect();
} catch (\LibreNMS\Exceptions\DatabaseConnectException $e) {
if (isCli()) {
echo 'MySQL Error: ' . $e->getMessage() . PHP_EOL;
} else {
echo "<h2>MySQL Error</h2><p>" . $e->getMessage() . "</p>";
}
exit(2);
}
$database_db = mysqli_select_db($database_link, $config['db_name']);
if (!$database_db) {
mysqli_query($database_link, "CREATE DATABASE " . $config['db_name'] . " CHARACTER SET utf8 COLLATE utf8_unicode_ci");
$database_db = mysqli_select_db($database_link, $config['db_name']);
}
dbQuery("SET NAMES 'utf8'");
dbQuery("SET CHARACTER SET 'utf8'");
dbQuery("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
// pull in the database config settings
mergedb();

View File

@ -141,6 +141,9 @@ db_port = int(config['db_port'])
if config['db_host'][:5].lower() == 'unix:':
db_server = config['db_host']
db_port = 0
elif config['db_socket']:
db_server = config['db_socket']
db_port = 0
else:
db_server = config['db_host']

View File

@ -82,6 +82,9 @@ db_port = int(config['db_port'])
if config['db_host'][:5].lower() == 'unix:':
db_server = config['db_host']
db_port = 0
elif config['db_socket']:
db_server = config['db_socket']
db_port = 0
else:
db_server = config['db_host']

View File

@ -91,6 +91,9 @@ db_password = config['db_pass']
if config['db_host'][:5].lower() == 'unix:':
db_server = config['db_host']
db_port = 0
elif config['db_socket']:
db_server = config['db_socket']
db_port = 0
elif ':' in config['db_host']:
db_server = config['db_host'].rsplit(':')[0]
db_port = int(config['db_host'].rsplit(':')[1])

View File

@ -40,9 +40,5 @@ if (getenv('DBTEST')) {
require $install_dir . '/includes/init.php';
chdir($install_dir);
$config['install_dir'] = $install_dir;
$config['mib_dir'] = $install_dir . '/mibs';
$config['snmpget'] = 'snmpget';
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_WARNING);

View File

@ -158,12 +158,14 @@ if (isset($config['user'])) {
}
// Run test on MySQL
$test_db = @mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name'], $config['db_port']);
if (mysqli_connect_error()) {
print_fail('Error connecting to your database '.mysqli_connect_error());
} else {
try {
dbConnect();
print_ok('Database connection successful');
} catch (\LibreNMS\Exceptions\DatabaseConnectException $e) {
print_fail('Error connecting to your database '.$e->getMessage());
}
// pull in the database config settings
mergedb();
// Test for MySQL Strict mode
$strict_mode = dbFetchCell("SELECT @@global.sql_mode");