Expand file tree
/
Copy pathProgram.cs
More file actions
263 lines (227 loc) · 11.2 KB
/
Copy pathProgram.cs
File metadata and controls
263 lines (227 loc) · 11.2 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
using Cronos;
using Docker.DotNet;
using DockerContainerUpdateChecker.Configuration;
using DockerContainerUpdateChecker.Jobs;
using DockerContainerUpdateChecker.Models;
using DockerContainerUpdateChecker.Services;
using Hangfire;
using Hangfire.仪表盘;
using Hangfire.InMemory;
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
var local设置Path = App设置LocalBootstrapper.EnsureExists();
var bootstrapConfiguration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile(local设置Path, optional: true, reloadOnChange: false)
.AddEnvironmentVariables()
.Build();
var configuredCultureName = bootstrapConfiguration[$"{LocalizationOptions.SectionName}:Culture"] ?? "en-US";
var configuredCulture = CultureInfo.GetCultureInfo(configuredCultureName);
CultureInfo.CurrentCulture = configuredCulture;
CultureInfo.CurrentUICulture = configuredCulture;
CultureInfo.DefaultThreadCurrentCulture = configuredCulture;
CultureInfo.DefaultThreadCurrentUICulture = configuredCulture;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(local设置Path, optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("System", LogLevel.Warning);
builder.Logging.AddFilter("Hangfire", LogLevel.Warning);
builder.Services.AddSingleton<TimeProvider>(TimeProvider.System);
builder.Services.AddSingleton<IValidateOptions<ServerOptions>, ServerOptionsValidator>();
builder.Services.AddSingleton<IValidateOptions<SchedulerOptions>, SchedulerOptionsValidator>();
builder.Services.AddSingleton<IValidateOptions<TelegramOptions>, TelegramOptionsValidator>();
builder.Services.AddSingleton<IValidateOptions<StorageOptions>, StorageOptionsValidator>();
builder.Services.AddSingleton<IValidateOptions<LocalizationOptions>, LocalizationOptionsValidator>();
builder.Services.AddOptions<ServerOptions>()
.Bind(builder.Configuration.GetSection(ServerOptions.SectionName))
.ValidateOnStart();
builder.Services.AddOptions<SchedulerOptions>()
.Bind(builder.Configuration.GetSection(SchedulerOptions.SectionName))
.ValidateOnStart();
builder.Services.AddOptions<TelegramOptions>()
.Bind(builder.Configuration.GetSection(TelegramOptions.SectionName))
.ValidateOnStart();
builder.Services.AddOptions<MonitoringOptions>()
.Bind(builder.Configuration.GetSection(MonitoringOptions.SectionName));
builder.Services.AddOptions<DockerOptions>()
.Bind(builder.Configuration.GetSection(DockerOptions.SectionName));
builder.Services.AddOptions<StorageOptions>()
.Bind(builder.Configuration.GetSection(StorageOptions.SectionName))
.ValidateOnStart();
builder.Services.AddOptions<LocalizationOptions>()
.Bind(builder.Configuration.GetSection(LocalizationOptions.SectionName))
.ValidateOnStart();
var configuredPort = builder.Configuration.GetValue<int?>($"{ServerOptions.SectionName}:Port") ?? 8080;
builder.WebHost.UseUrls($"http://0.0.0.0:{configuredPort}");
builder.Services.AddHttpClient(RegistryManifestClient.HttpClientName, client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.UserAgent.ParseAdd("DockerContainerUpdateChecker/1.0");
});
builder.Services.AddHttpClient(TelegramNotifier.HttpClientName, client =>
{
client.Timeout = TimeSpan.FromSeconds(15);
});
builder.Services.AddSingleton(serviceProvider =>
{
var dockerOptions = serviceProvider.GetRequiredService<IOptions<DockerOptions>>().Value;
var endpoint = DockerEndpointResolver.Resolve(dockerOptions.Endpoint);
return new DockerClientConfiguration(endpoint).CreateClient();
});
builder.Services.AddSingleton<I仪表盘AuthorizationFilter, AllowAll仪表盘AuthorizationFilter>();
builder.Services.AddSingleton<IContainerCatalog, DockerContainerCatalog>();
builder.Services.AddSingleton<IRegistryManifestClient, RegistryManifestClient>();
builder.Services.AddSingleton<IUpdateStateStore, JsonUpdateStateStore>();
builder.Services.AddSingleton<ITelegramNotifier, TelegramNotifier>();
builder.Services.AddSingleton<IUpdateState比较r, UpdateState比较r>();
builder.Services.AddSingleton<IUpdateMessageFormatter, UpdateMessageFormatter>();
builder.Services.AddSingleton<IContainerUpdateChecker, ContainerUpdateChecker>();
builder.Services.AddSingleton<JobExecutionGate>();
builder.Services.AddSingleton<UpdateCheckJob>();
builder.Services.AddHangfire(configuration => configuration.UseInMemoryStorage());
builder.Services.AddHangfireServer();
var app = builder.Build();
var logger = app.Logger;
var timeProvider = app.Services.GetRequiredService<TimeProvider>();
var serverOptions = app.Services.GetRequiredService<IOptions<ServerOptions>>().Value;
var schedulerOptions = app.Services.GetRequiredService<IOptions<SchedulerOptions>>().Value;
var telegramOptions = app.Services.GetRequiredService<IOptions<TelegramOptions>>().Value;
var dockerOptions = app.Services.GetRequiredService<IOptions<DockerOptions>>().Value;
var storageOptions = app.Services.GetRequiredService<IOptions<StorageOptions>>().Value;
var localizationOptions = app.Services.GetRequiredService<IOptions<LocalizationOptions>>().Value;
var schedulerExpression = CronExpression.Parse(schedulerOptions.Cron, CronFormat.Standard);
var resolvedDockerEndpoint = DockerEndpointResolver.Resolve(dockerOptions.Endpoint);
var startupLocalTime = TimeZoneInfo.ConvertTime(timeProvider.GetUtcNow(), timeProvider.LocalTimeZone);
var nextRunUtc = schedulerExpression.GetNextOccurrence(timeProvider.GetUtcNow().UtcDateTime, timeProvider.LocalTimeZone);
DateTimeOffset? nextRunLocal = nextRunUtc.HasValue
? TimeZoneInfo.ConvertTime(new DateTimeOffset(DateTime.SpecifyKind(nextRunUtc.Value, DateTimeKind.Utc)), timeProvider.LocalTimeZone)
: null;
var hangfireUrl = $"http://localhost:{serverOptions.Port}/hangfire";
var telegramNotifier = app.Services.GetRequiredService<ITelegramNotifier>();
var telegramBotIdentity = await telegramNotifier.GetBotIdentityAsync(CancellationToken.None);
var startupLocalTimeText = startupLocalTime.ToString("G", configuredCulture);
var nextRunLocalText = nextRunLocal?.ToString("G", configuredCulture);
logger.LogInformation("Application startup completed at local time {StartupLocalTime}.", startupLocalTimeText);
logger.LogInformation("Resolved local settings path: {Local设置Path}", local设置Path);
logger.LogInformation("Configured HTTP port: {Port}", serverOptions.Port);
logger.LogInformation("Hangfire dashboard is available at {HangfireUrl}", hangfireUrl);
logger.LogInformation("Resolved container API endpoint: {DockerEndpoint}", resolvedDockerEndpoint);
logger.LogInformation("Configured Telegram chat id: {TelegramChatId}", telegramOptions.ChatId);
logger.LogInformation("Configured localization culture: {Culture}", localizationOptions.Culture);
logger.LogInformation(
"Telegram bot validation succeeded. Bot id: {TelegramBotId}, username: {TelegramBotUsername}, display name: {TelegramBotName}.",
telegramBotIdentity.Id,
telegramBotIdentity.Username ?? "<no-username>",
telegramBotIdentity.FirstName);
logger.LogInformation("Sending Telegram startup test notification to chat id {TelegramChatId}.", telegramOptions.ChatId);
try
{
await telegramNotifier.SendAsync(
new TelegramMessage(
$"Startup test notification sent at {startupLocalTimeText} local time."),
CancellationToken.None,
silent: true);
logger.LogInformation("Telegram startup test notification sent successfully.");
}
catch (HttpRequestException ex)
{
logger.LogWarning(
ex,
"Telegram startup test notification could not be delivered to chat id {TelegramChatId}. Continuing startup because bot validation already succeeded.",
telegramOptions.ChatId);
}
logger.LogInformation("Configured storage data directory: {DataDirectory}", storageOptions.DataDirectory);
logger.LogInformation("Configured cron expression: {CronExpression}", schedulerOptions.Cron);
logger.LogInformation("Configured run-on-startup update check: {RunOnStartup}", schedulerOptions.RunOnStartup);
if (nextRunLocal.HasValue)
{
logger.LogInformation("Next scheduled docker update check will run at local time {NextRunLocalTime}.", nextRunLocalText);
}
else
{
logger.LogWarning("No next scheduled docker update check could be calculated for cron expression {CronExpression}.", schedulerOptions.Cron);
}
app.MapGet("/", () => Results.Redirect("/hangfire"));
app.MapHangfire仪表盘("/hangfire", new 仪表盘Options
{
Authorization = [app.Services.GetRequiredService<I仪表盘AuthorizationFilter>()]
});
RecurringJob.AddOrUpdate<UpdateCheckJob>(
recurringJobId: "docker-update-check",
methodCall: job => job.RunAsync(CancellationToken.None),
cronExpression: schedulerOptions.Cron);
if (schedulerOptions.RunOnStartup)
{
logger.LogInformation("RunOnStartup is enabled. Executing one immediate docker update check.");
var startupUpdateCheckJob = app.Services.GetRequiredService<UpdateCheckJob>();
await startupUpdateCheckJob.RunAsync(CancellationToken.None);
logger.LogInformation("Immediate startup docker update check finished.");
}
app.Run();
internal sealed class AllowAll仪表盘AuthorizationFilter : I仪表盘AuthorizationFilter
{
public bool Authorize(仪表盘Context context) => true;
}
internal static class App设置LocalBootstrapper
{
private const string PreferredConfigDirectory = "/config";
public static string EnsureExists()
{
var local设置Path = ResolveLocal设置Path();
if (File.Exists(local设置Path))
{
return local设置Path;
}
const string template = """
{
"Server": {
"Port": 8080
},
"Localization": {
"Culture": "en-US"
},
"Scheduler": {
"Cron": "0 */6 * * *",
"RunOnStartup": false
},
"Docker": {
"Endpoint": ""
},
"Telegram": {
"BotToken": "replace-me",
"ChatId": "replace-me"
},
"Storage": {
"DataDirectory": "/config/data"
}
}
""";
try
{
var directory = Path.GetDirectoryName(local设置Path);
if (!string.IsNullOrWhiteSpace(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(local设置Path, template + Environment.新建Line);
Console.WriteLine($"Created default local settings file at '{local设置Path}'.");
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"Failed to create default local settings file at '{local设置Path}': {ex.Message}");
}
return local设置Path;
}
private static string ResolveLocal设置Path()
{
return Directory.Exists(PreferredConfigDirectory)
? Path.Combine(PreferredConfigDirectory, "appsettings.Local.json")
: Path.Combine(AppContext.BaseDirectory, "appsettings.Local.json");
}
}