| | | 1 | | using System.Data; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using OzonRepositories.Context; |
| | | 5 | | |
| | | 6 | | namespace OzonOrdersWeb.WebServices.JobLogs; |
| | | 7 | | |
| | | 8 | | public sealed class ServerDiagnosticsService : IServerDiagnosticsService |
| | | 9 | | { |
| | | 10 | | private readonly ApplicationDbContext _context; |
| | | 11 | | private readonly DatabaseIoRateTracker _ioRateTracker; |
| | 0 | 12 | | private readonly DateTime _processStartedAtUtc = Process.GetCurrentProcess().StartTime.ToUniversalTime(); |
| | | 13 | | |
| | 0 | 14 | | public ServerDiagnosticsService(ApplicationDbContext context, DatabaseIoRateTracker ioRateTracker) |
| | | 15 | | { |
| | 0 | 16 | | _context = context; |
| | 0 | 17 | | _ioRateTracker = ioRateTracker; |
| | 0 | 18 | | } |
| | | 19 | | |
| | | 20 | | public async Task<ServerDiagnosticsSnapshot> GetSnapshotAsync(CancellationToken cancellationToken = default) |
| | | 21 | | { |
| | 0 | 22 | | var capturedAtUtc = DateTime.UtcNow; |
| | 0 | 23 | | var process = Process.GetCurrentProcess(); |
| | 0 | 24 | | var elapsed = Math.Max(1, (capturedAtUtc - _processStartedAtUtc).TotalSeconds); |
| | 0 | 25 | | var cpuPercent = Math.Min(100, process.TotalProcessorTime.TotalSeconds / elapsed / Environment.ProcessorCount * |
| | 0 | 26 | | var drive = GetApplicationDrive(); |
| | | 27 | | try |
| | | 28 | | { |
| | 0 | 29 | | var database = await ReadDatabaseMetricsAsync(cancellationToken); |
| | 0 | 30 | | var failedJobs = await _context.BackgroundJobExecutions.AsNoTracking() |
| | 0 | 31 | | .CountAsync(x => x.Status == "Failed" && x.StartedAt >= capturedAtUtc.AddHours(-24), cancellationToken); |
| | 0 | 32 | | var rates = _ioRateTracker.Update(capturedAtUtc, database.ReadBytes, database.WriteBytes); |
| | 0 | 33 | | return new ServerDiagnosticsSnapshot |
| | 0 | 34 | | { |
| | 0 | 35 | | CapturedAtUtc = capturedAtUtc, |
| | 0 | 36 | | ServerStatus = "Работает", |
| | 0 | 37 | | ProcessorCount = Environment.ProcessorCount, |
| | 0 | 38 | | ProcessCpuPercent = cpuPercent, |
| | 0 | 39 | | ProcessMemoryBytes = process.WorkingSet64, |
| | 0 | 40 | | AvailableMemoryBytes = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, |
| | 0 | 41 | | DiskTotalBytes = drive?.TotalSize ?? 0, |
| | 0 | 42 | | DiskFreeBytes = drive?.AvailableFreeSpace ?? 0, |
| | 0 | 43 | | DatabaseStatus = "Доступна", |
| | 0 | 44 | | DatabaseVersion = database.Version, |
| | 0 | 45 | | DatabaseSizeBytes = database.SizeBytes, |
| | 0 | 46 | | DatabaseReadLatencyMs = database.ReadLatencyMs, |
| | 0 | 47 | | DatabaseReadBytesPerSecond = rates.ReadBytesPerSecond, |
| | 0 | 48 | | DatabaseWriteBytesPerSecond = rates.WriteBytesPerSecond, |
| | 0 | 49 | | DatabaseReadBytesTotal = database.ReadBytes, |
| | 0 | 50 | | DatabaseWriteBytesTotal = database.WriteBytes, |
| | 0 | 51 | | DatabaseConnections = database.Connections, |
| | 0 | 52 | | DatabaseRunningThreads = database.RunningThreads, |
| | 0 | 53 | | DatabaseSlowQueries = database.SlowQueries, |
| | 0 | 54 | | FailedJobsLast24Hours = failedJobs |
| | 0 | 55 | | }; |
| | | 56 | | } |
| | 0 | 57 | | catch (Exception exception) |
| | | 58 | | { |
| | 0 | 59 | | return new ServerDiagnosticsSnapshot |
| | 0 | 60 | | { |
| | 0 | 61 | | CapturedAtUtc = capturedAtUtc, |
| | 0 | 62 | | ServerStatus = "Работает", |
| | 0 | 63 | | ProcessorCount = Environment.ProcessorCount, |
| | 0 | 64 | | ProcessCpuPercent = cpuPercent, |
| | 0 | 65 | | ProcessMemoryBytes = process.WorkingSet64, |
| | 0 | 66 | | AvailableMemoryBytes = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, |
| | 0 | 67 | | DiskTotalBytes = drive?.TotalSize ?? 0, |
| | 0 | 68 | | DiskFreeBytes = drive?.AvailableFreeSpace ?? 0, |
| | 0 | 69 | | DatabaseError = exception.Message, |
| | 0 | 70 | | FailedJobsLast24Hours = 0 |
| | 0 | 71 | | }; |
| | | 72 | | } |
| | 0 | 73 | | } |
| | | 74 | | |
| | | 75 | | private async Task<DatabaseMetrics> ReadDatabaseMetricsAsync(CancellationToken cancellationToken) |
| | | 76 | | { |
| | 0 | 77 | | var connection = _context.Database.GetDbConnection(); |
| | 0 | 78 | | var shouldClose = connection.State != ConnectionState.Open; |
| | 0 | 79 | | if (shouldClose) |
| | 0 | 80 | | await connection.OpenAsync(cancellationToken); |
| | | 81 | | |
| | | 82 | | try |
| | | 83 | | { |
| | 0 | 84 | | var startedAt = Stopwatch.GetTimestamp(); |
| | 0 | 85 | | var version = await ExecuteScalarAsync(connection, "SELECT VERSION()", cancellationToken) ?? "Неизвестная ве |
| | 0 | 86 | | var readLatencyMs = Stopwatch.GetElapsedTime(startedAt).Milliseconds; |
| | 0 | 87 | | var sizeBytes = ToInt64(await ExecuteScalarAsync(connection, """ |
| | 0 | 88 | | SELECT COALESCE(SUM(data_length + index_length), 0) |
| | 0 | 89 | | FROM information_schema.tables |
| | 0 | 90 | | WHERE table_schema = DATABASE() |
| | 0 | 91 | | """, cancellationToken)); |
| | | 92 | | |
| | 0 | 93 | | var status = await ReadStatusAsync(connection, cancellationToken); |
| | 0 | 94 | | return new DatabaseMetrics( |
| | 0 | 95 | | version, |
| | 0 | 96 | | sizeBytes, |
| | 0 | 97 | | readLatencyMs, |
| | 0 | 98 | | status.GetValueOrDefault("Innodb_data_read"), |
| | 0 | 99 | | status.GetValueOrDefault("Innodb_data_written"), |
| | 0 | 100 | | status.GetValueOrDefault("Threads_connected"), |
| | 0 | 101 | | status.GetValueOrDefault("Threads_running"), |
| | 0 | 102 | | status.GetValueOrDefault("Slow_queries")); |
| | | 103 | | } |
| | | 104 | | finally |
| | | 105 | | { |
| | 0 | 106 | | if (shouldClose) |
| | 0 | 107 | | await connection.CloseAsync(); |
| | | 108 | | } |
| | 0 | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | private static DriveInfo? GetApplicationDrive() => DriveInfo.GetDrives() |
| | 0 | 112 | | .Where(x => x.IsReady && AppContext.BaseDirectory.StartsWith(x.RootDirectory.FullName, StringComparison.OrdinalI |
| | 0 | 113 | | .OrderByDescending(x => x.RootDirectory.FullName.Length) |
| | 0 | 114 | | .FirstOrDefault(); |
| | | 115 | | |
| | | 116 | | private static async Task<string?> ExecuteScalarAsync(System.Data.Common.DbConnection connection, string commandText |
| | | 117 | | { |
| | 0 | 118 | | await using var command = connection.CreateCommand(); |
| | 0 | 119 | | command.CommandText = commandText; |
| | 0 | 120 | | var value = await command.ExecuteScalarAsync(cancellationToken); |
| | 0 | 121 | | return value?.ToString(); |
| | 0 | 122 | | } |
| | | 123 | | |
| | | 124 | | private static async Task<Dictionary<string, long>> ReadStatusAsync(System.Data.Common.DbConnection connection, Canc |
| | | 125 | | { |
| | 0 | 126 | | await using var command = connection.CreateCommand(); |
| | 0 | 127 | | command.CommandText = "SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected', 'Threads_running', 'Slow_ |
| | 0 | 128 | | await using var reader = await command.ExecuteReaderAsync(cancellationToken); |
| | 0 | 129 | | var result = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); |
| | 0 | 130 | | while (await reader.ReadAsync(cancellationToken)) |
| | 0 | 131 | | result[reader.GetString(0)] = ToInt64(reader.GetValue(1)?.ToString()); |
| | 0 | 132 | | return result; |
| | 0 | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | private static long ToInt64(string? value) => long.TryParse(value, out var result) ? result : 0; |
| | | 136 | | |
| | 0 | 137 | | private sealed record DatabaseMetrics(string Version, long SizeBytes, long ReadLatencyMs, long ReadBytes, |
| | 0 | 138 | | long WriteBytes, long Connections, long RunningThreads, long SlowQueries); |
| | | 139 | | } |