-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
289 lines (250 loc) · 10.6 KB
/
Copy pathProgram.cs
File metadata and controls
289 lines (250 loc) · 10.6 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
using ServerBackupManager.Models;
using ServerBackupManager.Services;
using ServerBackupManager.Services.Modules;
// ─────────────────────────────────────────────────────────────────────────────
// Çalışma modu seçimi:
// (argümansız) → yerel web arayüzünü başlatır
// --run [--module X] [--force] → penceresiz yedekleme çalıştırır (Task Scheduler/cron için)
// --help → yardım
// ─────────────────────────────────────────────────────────────────────────────
try { Console.OutputEncoding = System.Text.Encoding.UTF8; } catch { /* bazı konsollarda desteklenmez */ }
var argList = args.ToList();
if (argList.Contains("--help") || argList.Contains("-h"))
{
PrintHelp();
return;
}
if (argList.Contains("--run") || argList.Contains("run"))
{
await RunHeadless(argList);
return;
}
await RunWebUi();
return;
// ─────────────────────────────────────────────────────────────────────────────
static async Task RunHeadless(List<string> argList)
{
var config = ConfigStore.Load();
var log = new BackupLogger(writeToFile: true);
// Çakışan çalışmayı önle: önceki yedek hâlâ sürüyorsa atla.
using var runLock = RunLock.TryAcquire();
if (runLock is null)
{
log.Warn("Zaten çalışan bir yedekleme var; bu çalışma atlandı.");
Environment.Exit(0);
return;
}
string? onlyModule = GetArgValue(argList, "--module");
bool force = argList.Contains("--force");
try
{
await BackupRunner.RunAsync(config, log, onlyModule, force);
}
catch (Exception ex)
{
log.Error($"Yedekleme sırasında ölümcül hata: {ex.Message}");
}
BackupLogger.CleanupOldLogs(config.LogRetentionDays);
await NotificationService.NotifyAsync(config, log.HasErrors, log.Lines, log);
// Task Scheduler'ın başarısızlığı görebilmesi için hatalıysa sıfırdan farklı çıkış kodu.
Environment.Exit(log.HasErrors ? 1 : 0);
}
static async Task RunWebUi()
{
var config = ConfigStore.Load();
var port = FindAvailablePort(config.WebPort);
if (port != config.WebPort)
Console.WriteLine($"Port {config.WebPort} kullanımda; {port} kullanılıyor.");
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
builder.Services.ConfigureHttpJsonOptions(o =>
{
o.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
o.SerializerOptions.PropertyNameCaseInsensitive = true;
o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;
});
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
const string KeepSentinel = "__KEEP__";
// Mevcut yapılandırmayı (parolalar maskelenmiş) döndür.
app.MapGet("/api/config", () =>
{
var cfg = ConfigStore.Load();
MaskPasswords(cfg, KeepSentinel);
return Results.Json(cfg, ConfigJson);
});
// Yapılandırmayı kaydet.
app.MapPost("/api/config", async (HttpRequest req) =>
{
try
{
var incoming = await JsonSerializer.DeserializeAsync<AppConfig>(req.Body, ConfigJson);
if (incoming is null) return Results.BadRequest(new { error = "Geçersiz yapılandırma." });
var existing = ConfigStore.Load();
ReconcilePassword(incoming.Mssql, existing.Mssql, KeepSentinel, (m, v) => m.Password = v, m => m.Password);
ReconcilePassword(incoming.MySql, existing.MySql, KeepSentinel, (m, v) => m.Password = v, m => m.Password);
ReconcilePassword(incoming.Mongo, existing.Mongo, KeepSentinel, (m, v) => m.Password = v, m => m.Password);
ReconcilePassword(incoming.Notifications, existing.Notifications, KeepSentinel, (m, v) => m.SmtpPassword = v, m => m.SmtpPassword);
ConfigStore.Save(incoming);
return Results.Json(new { ok = true });
}
catch (Exception ex)
{
return Results.Json(new { ok = false, error = ex.Message }, statusCode: 500);
}
});
// Bağlantı testi (kaydedilmiş yapılandırma üzerinden).
app.MapPost("/api/test/{module}", async (string module) =>
{
var cfg = ConfigStore.Load();
TestResult result = module.ToLowerInvariant() switch
{
"mssql" => await ConnectionTester.TestMssqlAsync(cfg.Mssql),
"mysql" => await ConnectionTester.TestMySqlAsync(cfg.MySql),
"mongo" => await ConnectionTester.TestMongoAsync(cfg.Mongo),
"folder" => ConnectionTester.TestFolder(cfg.Folder),
_ => new TestResult(false, "Bilinmeyen modül.")
};
return Results.Json(result);
});
// Test bildirimi gönder (kaydedilmiş ayarlarla).
app.MapPost("/api/test/notification", async () =>
{
var cfg = ConfigStore.Load();
var result = await NotificationService.SendTestAsync(cfg);
return Results.Json(result);
});
// Her modülün son yedek durumu (hedef klasördeki en yeni zaman damgasına göre).
app.MapGet("/api/status", () =>
{
var cfg = ConfigStore.Load();
var list = BackupRunner.AllModules.Select(m =>
{
var s = m.GetSettings(cfg);
var last = BackupHelpers.GetLastBackup(s.DestinationFolder, cfg.TimestampFormat);
return new
{
module = m.Name,
enabled = s.Enabled,
destination = s.DestinationFolder,
lastBackup = last?.ToString("yyyy-MM-dd HH:mm")
};
});
return Results.Json(list);
});
// Şimdi yedekle (throttle yok sayılır). İsteğe bağlı ?module=mssql|mysql|mongodb|...
app.MapPost("/api/run", async (string? module) =>
{
var cfg = ConfigStore.Load();
var log = new BackupLogger(writeToFile: true);
await BackupRunner.RunAsync(cfg, log, module, force: true);
BackupLogger.CleanupOldLogs(cfg.LogRetentionDays);
return Results.Json(new { lines = log.Lines });
});
// Zamanlanmış görev kurulumu için bilgi.
app.MapGet("/api/schedule-help", () =>
{
var exe = Environment.ProcessPath ?? "ServerBackupManager";
var isWin = OperatingSystem.IsWindows();
return Results.Json(new
{
exePath = exe,
isWindows = isWin,
runCommand = $"\"{exe}\" --run",
windowsSchtasks = $"schtasks /Create /TN \"ServerBackupManager\" /TR \"\\\"{exe}\\\" --run\" /SC DAILY /ST 03:00 /RU SYSTEM /F",
cron = $"0 3 * * * \"{exe}\" --run",
dataDir = AppPaths.DataDir
});
});
var url = $"http://127.0.0.1:{port}";
Console.WriteLine($"ServerBackupManager arayüzü: {url}");
Console.WriteLine($"Veri klasörü: {AppPaths.DataDir}");
Console.WriteLine("Kapatmak için Ctrl+C.");
TryOpenBrowser(url);
try
{
await app.RunAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Web sunucusu başlatılamadı: {ex.Message}");
Console.WriteLine("İpucu: Genel sekmesinden farklı bir port deneyin.");
Environment.Exit(1);
}
}
static int FindAvailablePort(int desired)
{
for (var p = desired; p <= desired + 20; p++)
{
try
{
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, p);
listener.Start();
listener.Stop();
return p;
}
catch (System.Net.Sockets.SocketException) { /* dolu, sonrakini dene */ }
}
return desired; // hepsi doluysa istenen portla dene (anlamlı hata için)
}
// ── Yardımcılar ──────────────────────────────────────────────────────────────
static void MaskPasswords(AppConfig cfg, string sentinel)
{
cfg.Mssql.Password = string.IsNullOrEmpty(cfg.Mssql.Password) ? "" : sentinel;
cfg.MySql.Password = string.IsNullOrEmpty(cfg.MySql.Password) ? "" : sentinel;
cfg.Mongo.Password = string.IsNullOrEmpty(cfg.Mongo.Password) ? "" : sentinel;
cfg.Notifications.SmtpPassword = string.IsNullOrEmpty(cfg.Notifications.SmtpPassword) ? "" : sentinel;
}
static void ReconcilePassword<T>(T incoming, T existing, string sentinel,
Action<T, string> set, Func<T, string> get)
{
var value = get(incoming);
if (value == sentinel)
set(incoming, get(existing)); // değişmedi → eski (şifreli) parolayı koru
// "" → temizlendi; başka değer → yeni düz metin (kaydederken şifrelenir)
}
static string? GetArgValue(List<string> argList, string key)
{
var idx = argList.IndexOf(key);
return idx >= 0 && idx + 1 < argList.Count ? argList[idx + 1] : null;
}
static void TryOpenBrowser(string url)
{
try
{
if (OperatingSystem.IsWindows())
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
else if (OperatingSystem.IsMacOS())
Process.Start("open", url);
else
Process.Start("xdg-open", url);
}
catch { /* tarayıcı açılamazsa kullanıcı URL'yi elle açar */ }
}
static void PrintHelp()
{
Console.WriteLine("""
ServerBackupManager — MSSQL / MySQL / MongoDB / Klasör yedekleme aracı
Kullanım:
ServerBackupManager Yerel web arayüzünü başlatır (ayar yapmak için)
ServerBackupManager --run Etkin modülleri penceresiz yedekler (Task Scheduler)
ServerBackupManager --run --force Bekleme süresini (MinIntervalHours) yok sayar
ServerBackupManager --run --module MSSQL Yalnızca belirtilen modülü çalıştırır
ServerBackupManager --help Bu yardımı gösterir
Veri/ayar klasörü SBM_DATA_DIR ortam değişkeniyle değiştirilebilir.
""");
}
static partial class Program
{
public static readonly JsonSerializerOptions ConfigJson = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
WriteIndented = false
};
}