Skip to content

Commit

Permalink
feat: 修改了 SharedData,准备支持多实例
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Apr 20, 2024
1 parent 666d666 commit 2640d64
Show file tree
Hide file tree
Showing 14 changed files with 122 additions and 110 deletions.
3 changes: 0 additions & 3 deletions CSharp-OpenBMCLAPI/FodyWeavers.xml

This file was deleted.

7 changes: 6 additions & 1 deletion CSharp-OpenBMCLAPI/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ namespace CSharpOpenBMCLAPI
{
public class Logger
{
public Logger()
private static readonly Logger _instance = new Logger();

// 通过单例控制来使得 Logger 类不会被创建多次,进而保证日志写入锁只有一个,保证日志输出不会错位
public static Logger Instance { get => _instance; }

private Logger()
{

}
Expand Down
86 changes: 44 additions & 42 deletions CSharp-OpenBMCLAPI/Modules/Cluster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace CSharpOpenBMCLAPI.Modules
/// </summary>
public class Cluster : RunnableBase
{
private ClusterInfo clusterInfo;
internal ClusterInfo clusterInfo;
private TokenManager token;
private HttpClient client;
public Guid guid;
Expand All @@ -37,6 +37,7 @@ public class Cluster : RunnableBase
internal IStorage storage;
protected AccessCounter counter;
public CancellationTokenSource cancellationSrc = new CancellationTokenSource();
internal ClusterRequiredData requiredData;
//List<Task> tasks = new List<Task>();

/// <summary>
Expand All @@ -45,16 +46,17 @@ public class Cluster : RunnableBase
/// <param name="info"></param>
/// <param name="token"></param>
/// <exception cref="Exception"></exception>
public Cluster(ClusterInfo info, TokenManager token) : base()
public Cluster(ClusterRequiredData requiredData) : base()
{
this.clusterInfo = info;
this.token = token;
this.requiredData = requiredData;
this.clusterInfo = requiredData.ClusterInfo;
this.token = requiredData.Token;
this.guid = Guid.NewGuid();

client = HttpRequest.client;
client.DefaultRequestHeaders.Authorization = new("Bearer", SharedData.Token?.Token.token);
client.DefaultRequestHeaders.Authorization = new("Bearer", requiredData.Token?.Token.token);

this.storage = new CachedStorage(new FileStorage(SharedData.Config.clusterFileDirectory));
this.storage = new CachedStorage(new FileStorage(ClusterRequiredData.Config.clusterFileDirectory));

this.counter = new();
InitializeSocket();
Expand Down Expand Up @@ -94,12 +96,12 @@ protected void InitializeSocket()
/// <returns></returns>
protected override int Run(string[] args)
{
SharedData.PluginManager.TriggerEvent(this, ProgramEventType.ClusterStarted);
requiredData.PluginManager.TriggerEvent(this, ProgramEventType.ClusterStarted);
// 工作进程启动
SharedData.Logger.LogSystem($"工作进程 {guid} 已启动");
Logger.Instance.LogSystem($"工作进程 {guid} 已启动");
Task<int> task = AsyncRun();
task.Wait();
SharedData.PluginManager.TriggerEvent(this, ProgramEventType.ClusterStopped);
requiredData.PluginManager.TriggerEvent(this, ProgramEventType.ClusterStopped);
return task.Result;
}

Expand All @@ -115,7 +117,7 @@ protected async Task<int> AsyncRun()
// await GetConfiguration();
// 检查文件
//await CheckFiles();
SharedData.Logger.LogInfo();
Logger.Instance.LogInfo();
//Connect();

//await RequestCertification();
Expand All @@ -126,7 +128,7 @@ protected async Task<int> AsyncRun()

//await Enable();

SharedData.Logger.LogSystem($"工作进程 {guid} 在 <{SharedData.Config.HOST}:{SharedData.Config.PORT}> 提供服务");
Logger.Instance.LogSystem($"工作进程 {guid} 在 <{ClusterRequiredData.Config.HOST}:{ClusterRequiredData.Config.PORT}> 提供服务");

_keepAlive = Task.Run(_KeepAlive, cancellationSrc.Token);

Expand Down Expand Up @@ -154,7 +156,7 @@ private void InitializeService()
{
//var builder = WebApplication.CreateBuilder();
X509Certificate2 cert = LoadAndConvertCert();
SimpleWebServer server = new(SharedData.Config.PORT, cert);//cert);
SimpleWebServer server = new(ClusterRequiredData.Config.PORT, cert);//cert);
server.Start();
/*
builder.WebHost.UseKestrel(options =>
Expand Down Expand Up @@ -209,12 +211,12 @@ private void InitializeService()
/// </returns>
protected X509Certificate2 LoadAndConvertCert()
{
X509Certificate2 cert = X509Certificate2.CreateFromPemFile(Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications/cert.pem"),
Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications/key.pem"));
X509Certificate2 cert = X509Certificate2.CreateFromPemFile(Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications/cert.pem"),
Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications/key.pem"));
//return cert;
byte[] pfxCert = cert.Export(X509ContentType.Pfx);
SharedData.Logger.LogDebug($"将 PEM 格式的证书转换为 PFX 格式");
using (var file = File.Create(Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications/cert.pfx")))
Logger.Instance.LogDebug($"将 PEM 格式的证书转换为 PFX 格式");
using (var file = File.Create(Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications/cert.pfx")))
{
file.Write(pfxCert);
}
Expand All @@ -232,10 +234,10 @@ public void Connect()

this.socket.On("error", error => HandleError(error));
this.socket.On("message", msg => Utils.PrintResponseMessage(msg));
this.socket.On("connect", (_) => SharedData.Logger.LogInfo("与主控连接成功"));
this.socket.On("connect", (_) => Logger.Instance.LogInfo("与主控连接成功"));
this.socket.On("disconnect", (r) =>
{
SharedData.Logger.LogWarn($"与主控断开连接:{r}");
Logger.Instance.LogWarn($"与主控断开连接:{r}");
this.IsEnabled = false;
if (this.WantEnable)
{
Expand All @@ -253,7 +255,7 @@ public async Task Enable()
{
if (socket.Connected && IsEnabled)
{
SharedData.Logger.LogWarn($"试图在节点禁用且连接未断开时调用 Enable");
Logger.Instance.LogWarn($"试图在节点禁用且连接未断开时调用 Enable");
return;
}
await socket.EmitAsync("enable", (SocketIOResponse resp) =>
Expand All @@ -262,14 +264,14 @@ await socket.EmitAsync("enable", (SocketIOResponse resp) =>
this.WantEnable = true;
Utils.PrintResponseMessage(resp);
// Debugger.Break();
SharedData.Logger.LogSystem($"启用成功");
Logger.Instance.LogSystem($"启用成功");
}, new
{
host = SharedData.Config.HOST,
port = SharedData.Config.PORT,
version = SharedData.Config.clusterVersion,
byoc = SharedData.Config.bringYourOwnCertficate,
noFastEnable = SharedData.Config.noFastEnable,
host = ClusterRequiredData.Config.HOST,
port = ClusterRequiredData.Config.PORT,
version = ClusterRequiredData.Config.clusterVersion,
byoc = ClusterRequiredData.Config.bringYourOwnCertficate,
noFastEnable = ClusterRequiredData.Config.noFastEnable,
flavor = new
{
runtime = Utils.GetRuntime(),
Expand All @@ -287,13 +289,13 @@ public async Task Disable()
{
if (!this.IsEnabled)
{
SharedData.Logger.LogWarn($"试图在节点禁用时调用 Disable");
Logger.Instance.LogWarn($"试图在节点禁用时调用 Disable");
return;
}
await socket.EmitAsync("disable", (SocketIOResponse resp) =>
{
Utils.PrintResponseMessage(resp);
SharedData.Logger.LogSystem($"禁用成功");
Logger.Instance.LogSystem($"禁用成功");
this.IsEnabled = false;
});
if (this.WantEnable)
Expand All @@ -310,7 +312,7 @@ public async Task KeepAlive()
{
if (!this.IsEnabled)
{
SharedData.Logger.LogWarn($"试图在节点禁用时调用 KeepAlive");
Logger.Instance.LogWarn($"试图在节点禁用时调用 KeepAlive");
return;
}
string time = DateTime.Now.ToStandardTimeString();
Expand All @@ -319,7 +321,7 @@ await socket.EmitAsync("keep-alive",
(SocketIOResponse resp) =>
{
Utils.PrintResponseMessage(resp);
SharedData.Logger.LogSystem($"保活成功 at {time},served {Utils.GetLength(this.counter.bytes)}({this.counter.bytes} bytes)/{this.counter.hits} hits");
Logger.Instance.LogSystem($"保活成功 at {time},served {Utils.GetLength(this.counter.bytes)}({this.counter.bytes} bytes)/{this.counter.hits} hits");
this.counter.Reset();
},
new
Expand All @@ -331,9 +333,9 @@ await socket.EmitAsync("keep-alive",

using (var file = File.Create("totals.bson"))
{
lock (SharedData.DataStatistician)
lock (ClusterRequiredData.DataStatistician)
{
file.Write(Utils.BsonSerializeObject(SharedData.DataStatistician));
file.Write(Utils.BsonSerializeObject(ClusterRequiredData.DataStatistician));
}
}
}
Expand All @@ -354,12 +356,12 @@ public async Task GetConfiguration()
/// <returns></returns>
protected async Task CheckFiles()
{
if (SharedData.Config.skipStartupCheck || SharedData.Config.startupCheckMode == FileVerificationMode.None)
if (ClusterRequiredData.Config.skipStartupCheck || ClusterRequiredData.Config.startupCheckMode == FileVerificationMode.None)
{
return;
}
var resp = await this.client.GetAsync("openbmclapi/files");
SharedData.Logger.LogDebug($"文件检查策略:{SharedData.Config.startupCheckMode}");
Logger.Instance.LogDebug($"文件检查策略:{ClusterRequiredData.Config.startupCheckMode}");
byte[] bytes = await resp.Content.ReadAsByteArrayAsync();

UnpackBytes(ref bytes);
Expand Down Expand Up @@ -392,7 +394,7 @@ protected async Task CheckFiles()
{
count++;
}
SharedData.Logger.LogInfoNoNewLine($"\r{count}/{files.Count}");
Logger.Instance.LogInfoNoNewLine($"\r{count}/{files.Count}");
});

t.Cancel();
Expand All @@ -408,10 +410,10 @@ void CheckSingleFile(ApiFileInfo file)
string hash = file.hash;
long size = file.size;
DownloadFile(hash, path).Wait();
bool valid = VerifyFile(hash, size, SharedData.Config.startupCheckMode);
bool valid = VerifyFile(hash, size, ClusterRequiredData.Config.startupCheckMode);
if (!valid)
{
SharedData.Logger.LogWarn($"文件 {path} 损坏!期望哈希值为 {hash}");
Logger.Instance.LogWarn($"文件 {path} 损坏!期望哈希值为 {hash}");
DownloadFile(hash, path, true).Wait();
}
}
Expand Down Expand Up @@ -471,7 +473,7 @@ private async Task DownloadFile(string hash, string path, bool force = false)
var resp = await this.client.GetAsync($"openbmclapi/download/{hash}");

this.storage.WriteFile(Utils.HashToFileName(hash), await resp.Content.ReadAsByteArrayAsync());
SharedData.Logger.LogDebug($"文件 {path} 下载成功");
Logger.Instance.LogDebug($"文件 {path} 下载成功");
}

/// <summary>
Expand All @@ -480,9 +482,9 @@ private async Task DownloadFile(string hash, string path, bool force = false)
/// <returns></returns>
public async Task RequestCertification()
{
if (SharedData.Config.bringYourOwnCertficate)
if (ClusterRequiredData.Config.bringYourOwnCertficate)
{
SharedData.Logger.LogDebug($"{nameof(SharedData.Config.bringYourOwnCertficate)} 为 true,跳过请求证书……");
Logger.Instance.LogDebug($"{nameof(ClusterRequiredData.Config.bringYourOwnCertficate)} 为 true,跳过请求证书……");
return;
}
await socket.EmitAsync("request-cert", (SocketIOResponse resp) =>
Expand All @@ -496,10 +498,10 @@ await socket.EmitAsync("request-cert", (SocketIOResponse resp) =>
string? certString = cert.GetString();
string? keyString = key.GetString();
string certPath = Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications/cert.pem");
string keyPath = Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications/key.pem");
string certPath = Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications/cert.pem");
string keyPath = Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications/key.pem");
Directory.CreateDirectory(Path.Combine(SharedData.Config.clusterFileDirectory, $"certifications"));
Directory.CreateDirectory(Path.Combine(ClusterRequiredData.Config.clusterFileDirectory, $"certifications"));
using (var file = File.Create(certPath))
{
Expand Down
21 changes: 21 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/ClusterRequiredData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using CSharpOpenBMCLAPI.Modules.Plugin;
using CSharpOpenBMCLAPI.Modules.Statistician;

namespace CSharpOpenBMCLAPI.Modules
{
public class ClusterRequiredData
{
public static Config Config { get; set; } = new Config();
public Logger Logger { get => Logger.Instance; }
public ClusterInfo ClusterInfo { get; set; }
public TokenManager Token { get; set; }
public PluginManager PluginManager { get => PluginManager.Instance; }
public static DataStatistician DataStatistician { get; set; } = new DataStatistician();

public ClusterRequiredData(ClusterInfo info)
{
this.ClusterInfo = info;
this.Token = new(info);
}
}
}
2 changes: 1 addition & 1 deletion CSharp-OpenBMCLAPI/Modules/HttpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ static HttpRequest()
//BaseAddress = new Uri("https://openbmclapi.staging.bangbang93.com/")
BaseAddress = new Uri("https://openbmclapi.bangbang93.com/")
};
client.DefaultRequestHeaders.UserAgent.Add(new("openbmclapi-cluster", SharedData.Config.clusterVersion));
client.DefaultRequestHeaders.UserAgent.Add(new("openbmclapi-cluster", ClusterRequiredData.Config.clusterVersion));
}
}
}
Loading

0 comments on commit 2640d64

Please sign in to comment.