| | | 1 | | using System.Data.Common; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using Microsoft.Extensions.Configuration; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using OzonRepositories.Context; |
| | | 6 | | using OzonRepositories.Context.Identity; |
| | | 7 | | |
| | | 8 | | namespace Services.ApiServices; |
| | | 9 | | |
| | | 10 | | public class DatabaseHealthChecker |
| | | 11 | | { |
| | | 12 | | private readonly IServiceProvider _serviceProvider; |
| | | 13 | | private readonly IConfiguration _configuration; |
| | | 14 | | private readonly bool _isProd; |
| | | 15 | | |
| | 0 | 16 | | public DatabaseHealthChecker( |
| | 0 | 17 | | IServiceProvider serviceProvider, |
| | 0 | 18 | | IConfiguration configuration, |
| | 0 | 19 | | bool isProd) |
| | | 20 | | { |
| | 0 | 21 | | _serviceProvider = serviceProvider; |
| | 0 | 22 | | _configuration = configuration; |
| | 0 | 23 | | _isProd = isProd; |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async Task CheckAndPrintDatabaseHealthAsync() |
| | | 27 | | { |
| | 0 | 28 | | var results = new List<DatabaseHealthResult>(); |
| | | 29 | | |
| | | 30 | | // Проверка ApplicationDbContext |
| | 0 | 31 | | await CheckDbContextAsync<ApplicationDbContext>( |
| | 0 | 32 | | results, |
| | 0 | 33 | | "ApplicationDbContext", |
| | 0 | 34 | | _isProd ? "MySqlConnectionProd" : "MySqlConnectionLocal"); |
| | | 35 | | |
| | | 36 | | // Проверка OzonIdentityOrderContext (использует тот же connection string) |
| | 0 | 37 | | await CheckDbContextAsync<OzonIdentityOrderContext>( |
| | 0 | 38 | | results, |
| | 0 | 39 | | "OzonIdentityOrderContext", |
| | 0 | 40 | | _isProd ? "MySqlConnectionProd" : "MySqlConnectionLocal"); |
| | | 41 | | |
| | | 42 | | // Проверка BitrixContext |
| | 0 | 43 | | await CheckDbContextAsync<BitrixContext>( |
| | 0 | 44 | | results, |
| | 0 | 45 | | "BitrixContext", |
| | 0 | 46 | | "BitrixConnectionProd"); |
| | | 47 | | |
| | | 48 | | // Проверка JcEtalonContext |
| | 0 | 49 | | await CheckDbContextAsync<JcEtalonContext>( |
| | 0 | 50 | | results, |
| | 0 | 51 | | "JcEtalonContext", |
| | 0 | 52 | | "JcEtalonConnectionProd"); |
| | | 53 | | |
| | | 54 | | // Проверка OzonApiContext (каталог ozon_products) |
| | 0 | 55 | | await CheckDbContextAsync<OzonApiContext>( |
| | 0 | 56 | | results, |
| | 0 | 57 | | "OzonApiContext", |
| | 0 | 58 | | "OzonApiConnectionProd"); |
| | | 59 | | |
| | | 60 | | // Вывод результатов в консоль |
| | 0 | 61 | | PrintResults(results); |
| | 0 | 62 | | } |
| | | 63 | | |
| | | 64 | | private async Task CheckDbContextAsync<TContext>( |
| | | 65 | | List<DatabaseHealthResult> results, |
| | | 66 | | string contextName, |
| | | 67 | | string connectionStringName) where TContext : DbContext |
| | | 68 | | { |
| | 0 | 69 | | var connectionString = _configuration.GetConnectionString(connectionStringName); |
| | | 70 | | |
| | 0 | 71 | | if (string.IsNullOrWhiteSpace(connectionString)) |
| | | 72 | | { |
| | 0 | 73 | | results.Add(new DatabaseHealthResult |
| | 0 | 74 | | { |
| | 0 | 75 | | ConnectionName = contextName, |
| | 0 | 76 | | Server = "N/A", |
| | 0 | 77 | | Database = "N/A", |
| | 0 | 78 | | Status = "Не настроен", |
| | 0 | 79 | | StatusColor = false |
| | 0 | 80 | | }); |
| | 0 | 81 | | return; |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | try |
| | | 85 | | { |
| | | 86 | | // Извлекаем информацию о сервере и базе данных из connection string |
| | 0 | 87 | | var (server, database) = ExtractConnectionInfo(connectionString); |
| | | 88 | | |
| | | 89 | | // Проверяем соединение через DbContext |
| | 0 | 90 | | using var scope = _serviceProvider.CreateScope(); |
| | 0 | 91 | | var context = scope.ServiceProvider.GetRequiredService<TContext>(); |
| | | 92 | | |
| | | 93 | | // Используем таймаут для проверки соединения |
| | 0 | 94 | | using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| | 0 | 95 | | var canConnect = await context.Database.CanConnectAsync(cts.Token); |
| | | 96 | | |
| | 0 | 97 | | results.Add(new DatabaseHealthResult |
| | 0 | 98 | | { |
| | 0 | 99 | | ConnectionName = contextName, |
| | 0 | 100 | | Server = server, |
| | 0 | 101 | | Database = database, |
| | 0 | 102 | | Status = canConnect ? "Успешно" : "Ошибка", |
| | 0 | 103 | | StatusColor = canConnect |
| | 0 | 104 | | }); |
| | 0 | 105 | | } |
| | 0 | 106 | | catch (Exception ex) |
| | | 107 | | { |
| | 0 | 108 | | var (server, database) = ExtractConnectionInfo(connectionString); |
| | 0 | 109 | | results.Add(new DatabaseHealthResult |
| | 0 | 110 | | { |
| | 0 | 111 | | ConnectionName = contextName, |
| | 0 | 112 | | Server = server, |
| | 0 | 113 | | Database = database, |
| | 0 | 114 | | Status = $"Ошибка: {ex.Message.Substring(0, Math.Min(30, ex.Message.Length))}...", |
| | 0 | 115 | | StatusColor = false |
| | 0 | 116 | | }); |
| | 0 | 117 | | } |
| | 0 | 118 | | } |
| | | 119 | | |
| | | 120 | | private (string Server, string Database) ExtractConnectionInfo(string connectionString) |
| | | 121 | | { |
| | | 122 | | try |
| | | 123 | | { |
| | | 124 | | // Используем DbConnectionStringBuilder для парсинга connection string |
| | 0 | 125 | | var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; |
| | | 126 | | |
| | 0 | 127 | | string server = "N/A"; |
| | 0 | 128 | | string database = "N/A"; |
| | | 129 | | |
| | | 130 | | // Пробуем разные варианты ключей для сервера |
| | 0 | 131 | | if (builder.ContainsKey("Server")) |
| | 0 | 132 | | server = builder["Server"]?.ToString() ?? "N/A"; |
| | 0 | 133 | | else if (builder.ContainsKey("Data Source")) |
| | 0 | 134 | | server = builder["Data Source"]?.ToString() ?? "N/A"; |
| | 0 | 135 | | else if (builder.ContainsKey("Host")) |
| | 0 | 136 | | server = builder["Host"]?.ToString() ?? "N/A"; |
| | | 137 | | |
| | | 138 | | // Пробуем разные варианты ключей для базы данных |
| | 0 | 139 | | if (builder.ContainsKey("Database")) |
| | 0 | 140 | | database = builder["Database"]?.ToString() ?? "N/A"; |
| | 0 | 141 | | else if (builder.ContainsKey("Initial Catalog")) |
| | 0 | 142 | | database = builder["Initial Catalog"]?.ToString() ?? "N/A"; |
| | | 143 | | |
| | | 144 | | // Ограничиваем длину для отображения |
| | 0 | 145 | | if (server.Length > 25) |
| | 0 | 146 | | server = server.Substring(0, 22) + "..."; |
| | 0 | 147 | | if (database.Length > 20) |
| | 0 | 148 | | database = database.Substring(0, 17) + "..."; |
| | | 149 | | |
| | 0 | 150 | | return (server, database); |
| | | 151 | | } |
| | 0 | 152 | | catch |
| | | 153 | | { |
| | 0 | 154 | | return ("N/A", "N/A"); |
| | | 155 | | } |
| | 0 | 156 | | } |
| | | 157 | | |
| | | 158 | | private void PrintResults(List<DatabaseHealthResult> results) |
| | | 159 | | { |
| | 0 | 160 | | Console.WriteLine("\n╔══════════════════════════════════════════════════════════════════════════════════════════ |
| | 0 | 161 | | Console.WriteLine("║ ПРОВЕРКА ПОДКЛЮЧЕНИЙ К БАЗАМ ДАННЫХ |
| | 0 | 162 | | Console.WriteLine("╠════════════════════════════════════════════════════════════════════════════════════════════ |
| | 0 | 163 | | Console.WriteLine("║Имя подключения │Сервер │База данных │Стату |
| | 0 | 164 | | Console.WriteLine("╠════════════════════════════════════════════════════════════════════════════════════════════ |
| | | 165 | | |
| | 0 | 166 | | foreach (var result in results) |
| | | 167 | | { |
| | 0 | 168 | | string connectionName = result.ConnectionName.PadRight(35).Substring(0, 35); |
| | 0 | 169 | | string server = result.Server.PadRight(25).Substring(0, 25); |
| | 0 | 170 | | string database = result.Database.PadRight(22).Substring(0, 22); |
| | 0 | 171 | | string status = result.Status.PadRight(9).Substring(0, 9); |
| | | 172 | | |
| | 0 | 173 | | string colorCode = result.StatusColor ? "\x1b[32m" : "\x1b[31m"; |
| | 0 | 174 | | Console.WriteLine($"║{connectionName}│{server}│{database}│{colorCode}{status}\x1b[0m║"); |
| | | 175 | | } |
| | | 176 | | |
| | 0 | 177 | | Console.WriteLine("╚════════════════════════════════════════════════════════════════════════════════════════════ |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | private class DatabaseHealthResult |
| | | 181 | | { |
| | 0 | 182 | | public string ConnectionName { get; set; } = string.Empty; |
| | 0 | 183 | | public string Server { get; set; } = string.Empty; |
| | 0 | 184 | | public string Database { get; set; } = string.Empty; |
| | 0 | 185 | | public string Status { get; set; } = string.Empty; |
| | 0 | 186 | | public bool StatusColor { get; set; } |
| | | 187 | | } |
| | | 188 | | } |
| | | 189 | | |