Quellcode durchsuchen

- Fixed PostgreSQL support in install-eye.sh on ALT Linux
- HTML: Added support for multiple database backends

Dmitriev Roman vor 4 Monaten
Ursprung
Commit
70a8fb1fdc
4 geänderte Dateien mit 133 neuen und 56 gelöschten Zeilen
  1. 1 1
      html/inc/common.php
  2. 55 26
      html/inc/sql.php
  3. 75 27
      install-eye.sh
  4. 2 2
      scripts/eyelib/database.pm

+ 1 - 1
html/inc/common.php

@@ -3194,7 +3194,7 @@ function get_cacti_graph($host_ip, $port_index)
         return;
         return;
     }
     }
 
 
-    $cacti_db_link = new_connection(CACTI_DB_HOST, CACTI_DB_USER, CACTI_DB_PASS, CACTI_DB_NAME);
+    $cacti_db_link = new_connection('mysql',CACTI_DB_HOST, CACTI_DB_USER, CACTI_DB_PASS, CACTI_DB_NAME);
     if (!$cacti_db_link) {
     if (!$cacti_db_link) {
         return FALSE;
         return FALSE;
     }
     }

+ 55 - 26
html/inc/sql.php

@@ -48,60 +48,89 @@ function db_escape($connection, $value) {
     }
     }
 }
 }
 
 
-function new_connection ($db_host, $db_user, $db_password, $db_name)
+function new_connection ($db_type, $db_host, $db_user, $db_password, $db_name)
 {
 {
     // Создаем временный логгер для отладки до установки соединения
     // Создаем временный логгер для отладки до установки соединения
     $temp_debug_message = function($message) {
     $temp_debug_message = function($message) {
         error_log("DB_CONNECTION_DEBUG: " . $message);
         error_log("DB_CONNECTION_DEBUG: " . $message);
     };
     };
-    
+
     $temp_debug_message("Starting new_connection function");
     $temp_debug_message("Starting new_connection function");
-    $temp_debug_message("DB parameters - host: $db_host, user: $db_user, db: $db_name");
-    
+    $temp_debug_message("DB parameters - type: $db_type, host: $db_host, user: $db_user, db: $db_name");
+
     try {
     try {
         $temp_debug_message("Constructing DSN");
         $temp_debug_message("Constructing DSN");
-        $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
-        $temp_debug_message("DSN: $dsn");
         
         
+        // Определяем DSN в зависимости от типа базы данных
+        $dsn = "";
         $options = [
         $options = [
             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
             PDO::ATTR_EMULATE_PREPARES => false,
             PDO::ATTR_EMULATE_PREPARES => false,
-            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
         ];
         ];
         
         
-        $temp_debug_message("Attempting to create PDO connection");
-        $temp_debug_message("PDO options: " . json_encode($options));
+        if ($db_type === 'mysql') {
+            $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
+            $options[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8mb4";
+        } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
+            $dsn = "pgsql:host=$db_host;dbname=$db_name;options='--client_encoding=UTF8'";
+            $options[PDO::ATTR_PERSISTENT] = true; // Опционально: включение постоянных соединений для PostgreSQL
+        } else {
+            throw new Exception("Unsupported database type: $db_type. Supported types: mysql, pgsql");
+        }
         
         
+        $temp_debug_message("DSN: $dsn");
+        $temp_debug_message("PDO options: " . json_encode($options));
+        $temp_debug_message("Attempting to create PDO connection");
+
         $result = new PDO($dsn, $db_user, $db_password, $options);
         $result = new PDO($dsn, $db_user, $db_password, $options);
-        
+
         // Теперь у нас есть соединение, можем использовать LOG_DEBUG
         // Теперь у нас есть соединение, можем использовать LOG_DEBUG
         $temp_debug_message("PDO connection created successfully");
         $temp_debug_message("PDO connection created successfully");
-        $temp_debug_message("PDO connection info: " . $result->getAttribute(PDO::ATTR_CONNECTION_STATUS));
-        $temp_debug_message("PDO client version: " . $result->getAttribute(PDO::ATTR_CLIENT_VERSION));
-        $temp_debug_message("PDO server version: " . $result->getAttribute(PDO::ATTR_SERVER_VERSION));
-        
-        // Проверка кодировки
-        $stmt = $result->query("SHOW VARIABLES LIKE 'character_set_connection'");
-        $charset = $stmt->fetch(PDO::FETCH_ASSOC);
-        $temp_debug_message("Database character set: " . ($charset['Value'] ?? 'not set'));
+        $temp_debug_message("PDO connection info: " . ($result->getAttribute(PDO::ATTR_CONNECTION_STATUS) ?? 'N/A for PostgreSQL'));
         
         
+        // Проверяем наличие атрибутов перед использованием
+        if ($db_type === 'mysql') {
+            $temp_debug_message("PDO client version: " . $result->getAttribute(PDO::ATTR_CLIENT_VERSION));
+            $temp_debug_message("PDO server version: " . $result->getAttribute(PDO::ATTR_SERVER_VERSION));
+            
+            // Проверка кодировки для MySQL
+            $stmt = $result->query("SHOW VARIABLES LIKE 'character_set_connection'");
+            $charset = $stmt->fetch(PDO::FETCH_ASSOC);
+            $temp_debug_message("Database character set: " . ($charset['Value'] ?? 'not set'));
+        } elseif ($db_type === 'pgsql' || $db_type === 'postgresql') {
+            // Проверка кодировки для PostgreSQL
+            $stmt = $result->query("SHOW server_encoding");
+            $charset = $stmt->fetch(PDO::FETCH_ASSOC);
+            $temp_debug_message("PostgreSQL server encoding: " . ($charset['server_encoding'] ?? 'not set'));
+            
+            // Получаем версию PostgreSQL
+            $stmt = $result->query("SELECT version()");
+            $version = $stmt->fetch(PDO::FETCH_ASSOC);
+            $temp_debug_message("PostgreSQL version: " . ($version['version'] ?? 'unknown'));
+        }
+
         return $result;
         return $result;
-        
+
     } catch (PDOException $e) {
     } catch (PDOException $e) {
         // Логируем ошибку через error_log, так как соединение не установлено
         // Логируем ошибку через error_log, так как соединение не установлено
-        error_log("DB_CONNECTION_ERROR: Failed to connect to MySQL");
-        error_log("DB_CONNECTION_ERROR: DSN: mysql:host=$db_host;dbname=$db_name;charset=utf8mb4");
+        error_log("DB_CONNECTION_ERROR: Failed to connect to $db_type");
+        error_log("DB_CONNECTION_ERROR: DSN: $dsn");
         error_log("DB_CONNECTION_ERROR: User: $db_user");
         error_log("DB_CONNECTION_ERROR: User: $db_user");
         error_log("DB_CONNECTION_ERROR: Error code: " . $e->getCode());
         error_log("DB_CONNECTION_ERROR: Error code: " . $e->getCode());
         error_log("DB_CONNECTION_ERROR: Error message: " . $e->getMessage());
         error_log("DB_CONNECTION_ERROR: Error message: " . $e->getMessage());
         error_log("DB_CONNECTION_ERROR: Trace: " . $e->getTraceAsString());
         error_log("DB_CONNECTION_ERROR: Trace: " . $e->getTraceAsString());
-        
+
         // Также выводим в консоль для немедленной обратной связи
         // Также выводим в консоль для немедленной обратной связи
-        echo "Error connect to MySQL " . PHP_EOL;
+        echo "Error connect to $db_type " . PHP_EOL;
         echo "Error message: " . $e->getMessage() . PHP_EOL;
         echo "Error message: " . $e->getMessage() . PHP_EOL;
-        echo "DSN: mysql:host=$db_host;dbname=$db_name;charset=utf8mb4" . PHP_EOL;
-        
+        echo "DSN: $dsn" . PHP_EOL;
+
+        exit();
+    } catch (Exception $e) {
+        // Обработка других исключений (например, неподдерживаемый тип БД)
+        error_log("DB_CONNECTION_ERROR: " . $e->getMessage());
+        echo "Error: " . $e->getMessage() . PHP_EOL;
         exit();
         exit();
     }
     }
 }
 }
@@ -1161,6 +1190,6 @@ function record_to_txt($db, $table, $id) {
     return hash_to_text($record);
     return hash_to_text($record);
 }
 }
 
 
-$db_link = new_connection(DB_HOST, DB_USER, DB_PASS, DB_NAME);
+$db_link = new_connection(DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_NAME);
 
 
 ?>
 ?>

+ 75 - 27
install-eye.sh

@@ -11,14 +11,6 @@ YELLOW='\033[1;33m'
 BLUE='\033[0;34m'
 BLUE='\033[0;34m'
 NC='\033[0m' # No Color
 NC='\033[0m' # No Color
 
 
-# Global variables
-MYSQL_PASSWORD=""
-POSTGRES_PASSWORD=""
-NA
-DB_TYPE="mysql"  # Default database type
-DB_NAME="stat"
-DB_USER="stat"
-
 # Output functions
 # Output functions
 print_info() {
 print_info() {
     echo -e "${GREEN}[INFO]${NC} $1"
     echo -e "${GREEN}[INFO]${NC} $1"
@@ -164,11 +156,11 @@ install_deps_altlinux() {
     apt-get update
     apt-get update
 
 
     # General utilities
     # General utilities
-    apt-get install -y git xxd wget fping hwdata
+    apt-get install -y git xxd wget fping hwdata rsync
 
 
     # Database installation based on selected type
     # Database installation based on selected type
     if [[ "$DB_TYPE" == "postgresql" ]]; then
     if [[ "$DB_TYPE" == "postgresql" ]]; then
-        apt-get install -y postgresql postgresql-client
+        apt-get install -y postgresql17 postgresql17-server postgresql17-contrib postgresql17-perl
     else
     else
         apt-get install -y mariadb-server mariadb-client
         apt-get install -y mariadb-server mariadb-client
     fi
     fi
@@ -176,7 +168,7 @@ install_deps_altlinux() {
     # Web server and PHP
     # Web server and PHP
     if [[ "$DB_TYPE" == "postgresql" ]]; then
     if [[ "$DB_TYPE" == "postgresql" ]]; then
         apt-get install -y apache2 \
         apt-get install -y apache2 \
-            php8.2 php8.2-pgsql php8.2-pdo-pgsql php8.2-intl php8.2-mbstring \
+            php8.2 php8.2-pgsql php8.2-pdo_pgsql php8.2-intl php8.2-mbstring \
             pear-Mail php8.2-snmp php8.2-zip \
             pear-Mail php8.2-snmp php8.2-zip \
             php8.2-fpm-fcgi apache2-mod_fcgid
             php8.2-fpm-fcgi apache2-mod_fcgid
     else
     else
@@ -232,7 +224,7 @@ install_deps_debian() {
     apt-get update
     apt-get update
 
 
     # General utilities
     # General utilities
-    apt-get install -y git xxd bsdmainutils pwgen wget fping ieee-data
+    apt-get install -y git xxd bsdmainutils pwgen wget fping ieee-data rsync
 
 
     # Database installation based on selected type
     # Database installation based on selected type
     if [[ "$DB_TYPE" == "postgresql" ]]; then
     if [[ "$DB_TYPE" == "postgresql" ]]; then
@@ -538,7 +530,7 @@ download_additional_scripts() {
     print_info "Downloading jsTree..."
     print_info "Downloading jsTree..."
     if wget -q https://github.com/vakata/jstree/archive/3.3.12.tar.gz -O jstree.tar.gz; then
     if wget -q https://github.com/vakata/jstree/archive/3.3.12.tar.gz -O jstree.tar.gz; then
         tar -xzf jstree.tar.gz -C /opt/Eye/html/js/
         tar -xzf jstree.tar.gz -C /opt/Eye/html/js/
-        mv /opt/Eye/html/js/jstree-3.3.12/dist/* /opt/Eye/html/js/jstree
+        rsync -a /opt/Eye/html/js/jstree-3.3.12/dist/ /opt/Eye/html/js/jstree/
         rm -rf /opt/Eye/html/js/jstree-3.3.12
         rm -rf /opt/Eye/html/js/jstree-3.3.12
         rm -f jstree.tar.gz
         rm -f jstree.tar.gz
     else
     else
@@ -676,6 +668,15 @@ EOF
 setup_postgresql() {
 setup_postgresql() {
     print_step "Configuring PostgreSQL"
     print_step "Configuring PostgreSQL"
 
 
+    PGDATA="/var/lib/pgsql/data"
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        echo "root ALL=(ALL:ALL) NOPASSWD: ALL" >/etc/sudoers.d/root
+        PGDATA="/var/lib/pgsql/data"
+        if [ -z "$(ls -A $PGDATA 2>/dev/null)" ]; then
+            /etc/init.d/postgresql initdb
+            fi
+        fi
+
     # Start and enable service
     # Start and enable service
     $SERVICE_MANAGER enable postgresql
     $SERVICE_MANAGER enable postgresql
     $SERVICE_MANAGER start postgresql
     $SERVICE_MANAGER start postgresql
@@ -703,7 +704,11 @@ setup_postgresql() {
     print_info "Importing database structure..."
     print_info "Importing database structure..."
 
 
     # Import main SQL file as postgres user
     # Import main SQL file as postgres user
-    sudo -u postgres psql -f ${SQL_CREATE_FILE}
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        psql -U postgres -f ${SQL_CREATE_FILE}
+        else
+        sudo -u postgres psql -f ${SQL_CREATE_FILE}
+        fi
 
 
     if [[ $? -ne 0 ]]; then
     if [[ $? -ne 0 ]]; then
         print_error "Error importing create_db.sql"
         print_error "Error importing create_db.sql"
@@ -714,11 +719,21 @@ setup_postgresql() {
 
 
     # Set password for stat user
     # Set password for stat user
     print_info "Setting password for user 'stat'..."
     print_info "Setting password for user 'stat'..."
-    sudo -u postgres psql -c "ALTER USER stat WITH PASSWORD '$DB_PASSWORD';"
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        psql -U postgres -c "CREATE USER stat WITH PASSWORD '$DB_PASSWORD';"
+        psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE stat TO stat;"
+        else
+        sudo -u postgres psql -c "CREATE USER stat WITH PASSWORD '$DB_PASSWORD';"
+        sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE stat TO stat;"
+        fi
 
 
     # Import data
     # Import data
     print_info "Importing initial data..."
     print_info "Importing initial data..."
-    sudo -u postgres psql -d stat -f ${SQL_DATA_FILE}
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        psql -U postgres -d stat -f ${SQL_DATA_FILE}
+        else
+        sudo -u postgres psql -d stat -f ${SQL_DATA_FILE}
+        fi
 
 
     if [[ $? -ne 0 ]]; then
     if [[ $? -ne 0 ]]; then
         print_warn "Error importing data.sql (data may already exist)"
         print_warn "Error importing data.sql (data may already exist)"
@@ -726,19 +741,52 @@ setup_postgresql() {
         print_info "Initial data imported"
         print_info "Initial data imported"
     fi
     fi
 
 
-    # Configure PostgreSQL for MD5 authentication
-    local pg_hba_file="/etc/postgresql/$(ls /etc/postgresql/ | head -1)/main/pg_hba.conf"
-    if [[ -f "$pg_hba_file" ]]; then
-        # Backup original
-        cp "$pg_hba_file" "${pg_hba_file}.backup"
-        
-        # Add local md5 authentication if not present
-        if ! grep -q "local.*stat.*md5" "$pg_hba_file"; then
-            echo "local   stat            stat                                    md5" >> "$pg_hba_file"
-            print_info "Added MD5 authentication for stat user in pg_hba.conf"
-        fi
+    # Grant privileges on all tables to stat user
+    print_info "Granting privileges on all tables to user 'stat'..."
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        psql -U postgres -d stat <<EOF
+GRANT ALL ON ALL TABLES IN SCHEMA public TO stat;
+GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO stat;
+GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO stat;
+EOF
+        else
+        sudo -u postgres psql -d stat <<EOF
+GRANT ALL ON ALL TABLES IN SCHEMA public TO stat;
+GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO stat;
+GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO stat;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO stat;
+EOF
     fi
     fi
 
 
+    # Configure PostgreSQL for MD5 authentication
+    if [[ "$OS_FAMILY" == "alt" ]]; then
+        local pg_hba_file="/var/lib/pgsql/data/pg_hba.conf"
+        if [[ -f "$pg_hba_file" ]]; then
+            # Backup original
+            cp "$pg_hba_file" "${pg_hba_file}.backup"
+            # Add local md5 authentication if not present
+            if ! grep -q "local.*stat.*md5" "$pg_hba_file"; then
+                echo "local   stat            stat                                    scram-sha-256" >> "$pg_hba_file"
+                print_info "Added MD5 authentication for stat user in pg_hba.conf"
+                fi
+            fi
+        else
+        local pg_hba_file="/etc/postgresql/$(ls /etc/postgresql/ | head -1)/main/pg_hba.conf"
+        if [[ -f "$pg_hba_file" ]]; then
+            # Backup original
+            cp "$pg_hba_file" "${pg_hba_file}.backup"
+            # Add local md5 authentication if not present
+            if ! grep -q "local.*stat.*md5" "$pg_hba_file"; then
+                echo "local   stat            stat                                    scram-sha-256" >> "$pg_hba_file"
+                print_info "Added MD5 authentication for stat user in pg_hba.conf"
+                fi
+            fi
+        fi
     # Restart PostgreSQL to apply changes
     # Restart PostgreSQL to apply changes
     $SERVICE_MANAGER restart postgresql
     $SERVICE_MANAGER restart postgresql
 
 

+ 2 - 2
scripts/eyelib/database.pm

@@ -1137,10 +1137,10 @@ $history_syslog_day = get_option($db,48);
 
 
 $history_trafstat_day = get_option($db,49);
 $history_trafstat_day = get_option($db,49);
 
 
-my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
+my $ou = get_record_sql($db,"SELECT id FROM OU WHERE COALESCE(default_users::integer, 0) = 1");
 if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
 if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
 
 
-$ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
+$ou = get_record_sql($db,"SELECT id FROM OU WHERE COALESCE(default_hotspot::integer, 0) = 1 ");
 if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
 if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
 
 
 @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
 @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');