-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
214 lines (193 loc) · 8.85 KB
/
Program.cs
File metadata and controls
214 lines (193 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PostgresBackupConsole.Logging;
using PostgresBackupConsole.Services;
class Program
{
// Shared between LogMessage and FileLoggerProvider so that direct writes
// and ILogger writes never interleave in the log file.
private static readonly object _logLock = new();
public static async Task<int> Main(string[] args) // Return int for exit code
{
// Read configuration up-front so we can honor PostgresSettings:LogPath
// before opening the log file (the host re-reads the same JSON later).
var configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var (logsDir, logPath, logPathFallbackReason) = ResolveLogPath(configuration);
StreamWriter fileStream;
try
{
Directory.CreateDirectory(logsDir);
fileStream = new StreamWriter(logPath, append: true);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to open log file '{logPath}': {ex.Message}");
return 1;
}
using (fileStream)
{
try
{
LogMessage("Starting PostgreSQL Backup Process...", fileStream);
if (logPathFallbackReason is not null)
{
LogMessage($"Warning: {logPathFallbackReason}", fileStream);
}
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
// Reuse the already-built configuration so the host
// sees exactly the same values we used for LogPath.
builder.Sources.Clear();
builder.AddConfiguration(configuration);
})
.ConfigureLogging(logging =>
{
// Route ILogger output (from PostgresService, etc.) into the
// same backup_log file via a shared writer + lock.
logging.AddProvider(new FileLoggerProvider(fileStream, _logLock));
})
.ConfigureServices((hostContext, services) =>
{
services.Configure<PostgresSettings>(
hostContext.Configuration.GetSection("PostgresSettings"));
services.AddScoped<IPostgresService, PostgresService>();
})
.Build();
var postgresService = host.Services.GetRequiredService<IPostgresService>();
var settings = host.Services.GetRequiredService<IOptions<PostgresSettings>>().Value;
// Display settings
LogMessage($"Using settings:", fileStream);
LogMessage($"Host: {settings.Host}", fileStream);
LogMessage($"Port: {settings.Port}", fileStream);
LogMessage($"Username: {settings.Username}", fileStream);
LogMessage($"Database: {settings.Database}", fileStream);
LogMessage($"Backup Type: {settings.BackupType}", fileStream);
LogMessage($"Retention Days: {settings.BackupRetentionDays}", fileStream);
LogMessage($"Log directory: {logsDir}", fileStream);
// Create backup directory
var backupPath = settings.BackupPath;
if (string.IsNullOrEmpty(backupPath))
{
backupPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backups");
LogMessage($"Warning: No backup path configured, using default: {backupPath}", fileStream);
}
Directory.CreateDirectory(backupPath);
LogMessage($"Backup directory: {backupPath}", fileStream);
// Get all databases
LogMessage("\nRetrieving database list...", fileStream);
var databases = await postgresService.GetAllDatabaseNames();
LogMessage($"Found {databases.Count} databases to backup:", fileStream);
foreach (var db in databases)
{
LogMessage($"- {db}", fileStream);
}
// Backup each database
LogMessage("\nStarting backup process...", fileStream);
foreach (var database in databases)
{
LogMessage($"\nBacking up database: {database}", fileStream);
var success = await postgresService.BackupDatabase(database, backupPath);
if (success)
LogMessage($"✓ Successfully backed up database: {database}", fileStream);
else
LogMessage($"✗ Failed to backup database: {database}", fileStream);
}
// Cleanup old backups
LogMessage("\nCleaning up old backups...", fileStream);
postgresService.CleanupOldBackups(backupPath, settings.BackupRetentionDays);
LogMessage("\nBackup process completed successfully!", fileStream);
CleanupOldLogs(logsDir, 30);
return 0; // Success exit code
}
catch (Exception ex)
{
// fileStream is still open here, so we can log directly to it
// without trying to open a second StreamWriter on the same path.
LogMessage($"\nERROR: {ex.Message}", fileStream);
LogMessage(ex.StackTrace ?? "No stack trace available", fileStream);
return 1; // Error exit code
}
}
}
/// <summary>
/// Resolves the directory used for backup logs and the full path of the log
/// file for this run. Honors <c>PostgresSettings:LogPath</c> from
/// <c>appsettings.json</c>; falls back to <c><exe-dir>\Logs</c> if the
/// configured path is empty or unusable. Returns a non-null
/// <paramref name="fallbackReason"/> when a fallback was used.
/// </summary>
private static (string LogsDir, string LogPath, string? FallbackReason) ResolveLogPath(IConfiguration configuration)
{
var defaultLogsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
var configuredLogsDir = configuration["PostgresSettings:LogPath"];
string logsDir = defaultLogsDir;
string? fallbackReason = null;
if (!string.IsNullOrWhiteSpace(configuredLogsDir))
{
try
{
// Path.GetFullPath validates the shape of the path without
// touching disk; the directory itself is created later.
logsDir = Path.GetFullPath(configuredLogsDir);
}
catch (Exception ex)
{
fallbackReason =
$"Configured LogPath '{configuredLogsDir}' is invalid ({ex.Message}); " +
$"falling back to '{defaultLogsDir}'.";
}
}
var logPath = Path.Combine(logsDir, $"backup_log_{DateTime.Now:yyyyMMdd_HHmmss}.txt");
return (logsDir, logPath, fallbackReason);
}
private static void CleanupOldLogs(string logsPath, int retentionDays)
{
try
{
var cutoffDate = DateTime.Now.AddDays(-retentionDays);
var files = Directory.GetFiles(logsPath, "backup_log_*.txt");
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
if (fileInfo.CreationTime < cutoffDate)
{
File.Delete(file);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to cleanup old logs: {ex.Message}");
}
}
private static void LogMessage(string message, StreamWriter fileStream)
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var logMessage = $"[{timestamp}] {message}";
// Still write to console for debugging purposes
Console.WriteLine(logMessage);
// Serialize with FileLoggerProvider so direct writes and ILogger writes
// never interleave a half-line in the log file.
lock (_logLock)
{
try
{
fileStream.WriteLine(logMessage);
fileStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write to log file: {ex.Message}");
}
}
}
}