95 lines
2.7 KiB
C#
95 lines
2.7 KiB
C#
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using Core;
|
|
using FluentScheduler;
|
|
using Interface.Jobs;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace Service.Jobs;
|
|
|
|
public class HealthyTaskRegistry : Registry, IHealthyTaskRegistry
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public HealthyTaskRegistry(IConfiguration configuration)
|
|
{
|
|
_configuration = configuration;
|
|
Schedule(Job).ToRunNow().AndEvery(2).Minutes();
|
|
}
|
|
|
|
public async void Job()
|
|
{
|
|
try
|
|
{
|
|
await JobExecute();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(e);
|
|
await WxNotify.SendCommonAsync($"HealthyTaskRegistry.Job() error: {e}");
|
|
}
|
|
}
|
|
|
|
private async Task JobExecute()
|
|
{
|
|
// 获取 配置 是个 KV 集合
|
|
var configs = _configuration.GetSection("HealthyTasks");
|
|
|
|
// 遍历配置
|
|
foreach (var item in configs.GetChildren())
|
|
{
|
|
// 获取配置的 containerName 和 url
|
|
var containerName = item["ContainerName"];
|
|
var url = item["Url"];
|
|
|
|
// 执行
|
|
await ExecuteItem(containerName!, url!);
|
|
}
|
|
}
|
|
|
|
private async Task ExecuteItem(string containerName, string url)
|
|
{
|
|
try
|
|
{
|
|
var client = new HttpClient();
|
|
|
|
// basic auth
|
|
string authInfo = Convert.ToBase64String(Encoding.ASCII.GetBytes("suncheng:SCsunch940622"));
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
|
|
|
|
var response = await client.GetAsync(url);
|
|
|
|
if (response.StatusCode != HttpStatusCode.OK)
|
|
{
|
|
throw new Exception($"StatusCode: {response.StatusCode}");
|
|
}
|
|
|
|
Console.WriteLine($"ContainerName: {containerName}, Url: {url}, StatusCode: {response.StatusCode}");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(e);
|
|
await WxNotify.SendCommonAsync($"ExecuteItem {containerName} error: {e.Message}");
|
|
await ExecuteReboot(containerName);
|
|
}
|
|
}
|
|
|
|
private async Task ExecuteReboot(string containerName)
|
|
{
|
|
var command = $"docker restart {containerName}";
|
|
|
|
var (responseCode, message) = await Command.ExecAsync(command);
|
|
|
|
if (responseCode != HttpStatusCode.OK)
|
|
{
|
|
await WxNotify.SendCommonAsync($"ExecuteReboot {containerName} error: {responseCode} message: {message}");
|
|
}
|
|
else
|
|
{
|
|
await WxNotify.SendCommonAsync($"ContainerName: {containerName}");
|
|
}
|
|
}
|
|
} |