提交 91b167eb 编写于 作者: 麦壳饼's avatar 麦壳饼

重新整理了状态收集

上级 a8a7b98e
...@@ -20,9 +20,9 @@ namespace IoTSharp.Controllers ...@@ -20,9 +20,9 @@ namespace IoTSharp.Controllers
[ApiController] [ApiController]
public class MqttController : ControllerBase public class MqttController : ControllerBase
{ {
private readonly MqttEventsHandler _mqttService; private readonly MQTTService _mqttService;
public MqttController(MqttEventsHandler mqttService) public MqttController(MQTTService mqttService)
{ {
_mqttService = mqttService; _mqttService = mqttService;
} }
......
...@@ -52,7 +52,7 @@ namespace IoTSharp ...@@ -52,7 +52,7 @@ namespace IoTSharp
internal static void UseSwagger(this IApplicationBuilder app) internal static void UseSwagger(this IApplicationBuilder app)
{ {
app.UseSwaggerUi3(); app.UseSwaggerUi3();
app.UseSwagger(config => config.PostProcess = (document, request) => app.UseOpenApi(config => config.PostProcess = (document, request) =>
{ {
if (request.Headers.ContainsKey("X-External-Host")) if (request.Headers.ContainsKey("X-External-Host"))
{ {
......
...@@ -15,6 +15,9 @@ using MQTTnet.Server; ...@@ -15,6 +15,9 @@ using MQTTnet.Server;
using MQTTnet.Client.Receiving; using MQTTnet.Client.Receiving;
using MQTTnet.Client.Options; using MQTTnet.Client.Options;
using IoTSharp.MQTT; using IoTSharp.MQTT;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace IoTSharp namespace IoTSharp
{ {
...@@ -47,13 +50,13 @@ namespace IoTSharp ...@@ -47,13 +50,13 @@ namespace IoTSharp
}); });
services.AddMqttConnectionHandler(); services.AddMqttConnectionHandler();
services.AddMqttWebSocketServerAdapter(); services.AddMqttWebSocketServerAdapter();
services.AddTransient<MqttEventsHandler>(); services.AddTransient<MQTTService>();
} }
public static void UseIotSharpMqttServer(this IApplicationBuilder app) public static void UseIotSharpMqttServer(this IApplicationBuilder app)
{ {
app.UseMqttEndpoint(); app.UseMqttEndpoint();
var mqttEvents = app.ApplicationServices.CreateScope().ServiceProvider.GetService<MqttEventsHandler>(); var mqttEvents = app.ApplicationServices.CreateScope().ServiceProvider.GetService<MQTTService>();
IMqttServerStorage storage = app.ApplicationServices.CreateScope().ServiceProvider.GetService<IMqttServerStorage>(); IMqttServerStorage storage = app.ApplicationServices.CreateScope().ServiceProvider.GetService<IMqttServerStorage>();
app.UseMqttServerEx(server => app.UseMqttServerEx(server =>
{ {
server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(args => mqttEvents.Server_ClientConnected(server, args)); server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(args => mqttEvents.Server_ClientConnected(server, args));
...@@ -96,6 +99,7 @@ namespace IoTSharp ...@@ -96,6 +99,7 @@ namespace IoTSharp
}; };
} }
public static void AddMqttClient(this IServiceCollection services, MqttClientSetting setting) public static void AddMqttClient(this IServiceCollection services, MqttClientSetting setting)
{ {
if (setting == null) setting = new MqttClientSetting(); if (setting == null) setting = new MqttClientSetting();
...@@ -106,7 +110,76 @@ namespace IoTSharp ...@@ -106,7 +110,76 @@ namespace IoTSharp
.WithCredentials(setting.UserName, setting.Password) .WithCredentials(setting.UserName, setting.Password)
.WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500) .WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500)
.Build()); .Build());
services.AddHostedService <MqttClientService>(); services.AddHostedService<MqttClientService>();
}
public static void UseIotSharpSelfCollecting(this IApplicationBuilder app)
{
var _systemStatusService = app.ApplicationServices.CreateScope().ServiceProvider.GetService<RuntimeStatusHandler>();
var _creationTimestamp = DateTime.Now;
_systemStatusService.Set("startup.timestamp", _creationTimestamp);
_systemStatusService.Set("framework.description", RuntimeInformation.FrameworkDescription);
_systemStatusService.Set("process.architecture", RuntimeInformation.ProcessArchitecture);
_systemStatusService.Set("process.id", Process.GetCurrentProcess().Id);
_systemStatusService.Set("system.processor_count", Environment.ProcessorCount);
_systemStatusService.Set("system.working_set", () => Environment.WorkingSet);
_systemStatusService.Set("arguments", string.Join(" ", Environment.GetCommandLineArgs()));
_systemStatusService.Set("iotsharp.version", typeof(Startup).Assembly.GetName().Version.ToString());
_systemStatusService.Set("startup.duration", DateTime.Now - _creationTimestamp);
_systemStatusService.Set("system.date_time", () => DateTime.Now);
_systemStatusService.Set("up_time", () => DateTime.Now - _creationTimestamp);
_systemStatusService.Set("os.description", RuntimeInformation.OSDescription);
_systemStatusService.Set("os.architecture", RuntimeInformation.OSArchitecture);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_systemStatusService.Set("os.platform", "linux");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_systemStatusService.Set("os.platform", "windows");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
_systemStatusService.Set("os.platform", "osx");
}
_systemStatusService.Set("thread_pool.max_worker_threads", () =>
{
ThreadPool.GetMaxThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.max_completion_port_threads", () =>
{
ThreadPool.GetMaxThreads(out _, out var x);
return x;
});
_systemStatusService.Set("thread_pool.min_worker_threads", () =>
{
ThreadPool.GetMinThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.min_completion_port_threads", () =>
{
ThreadPool.GetMinThreads(out _, out var x);
return x;
});
_systemStatusService.Set("thread_pool.available_worker_threads", () =>
{
ThreadPool.GetAvailableThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.available_completion_port_threads", () =>
{
ThreadPool.GetAvailableThreads(out _, out var x);
return x;
});
} }
} }
......
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace IoTSharp.Handlers
{
public class SystemStatusHandler
{
private readonly RuntimeStatusHandler _systemStatusService;
private readonly ILogger _logger;
private readonly DateTime _creationTimestamp;
public SystemStatusHandler(
RuntimeStatusHandler systemStatusService,
ILogger<SystemStatusHandler> logger)
{
_systemStatusService = systemStatusService ?? throw new ArgumentNullException(nameof(systemStatusService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_creationTimestamp = DateTime.Now;
}
public event EventHandler ServicesInitialized;
public event EventHandler ConfigurationLoaded;
public event EventHandler StartupCompleted;
public void Start()
{
_systemStatusService.Set("startup.timestamp", _creationTimestamp);
_systemStatusService.Set("startup.duration", null);
_systemStatusService.Set("framework.description", RuntimeInformation.FrameworkDescription);
_systemStatusService.Set("process.architecture", RuntimeInformation.ProcessArchitecture);
_systemStatusService.Set("process.id", Process.GetCurrentProcess().Id);
_systemStatusService.Set("system.date_time", () => DateTime.Now);
_systemStatusService.Set("system.processor_count", Environment.ProcessorCount);
_systemStatusService.Set("system.working_set", () => Environment.WorkingSet);
_systemStatusService.Set("up_time", () => DateTime.Now - _creationTimestamp);
_systemStatusService.Set("arguments", string.Join(" ", Environment.GetCommandLineArgs()));
_systemStatusService.Set("iotsharp.version", typeof(Startup).Assembly.GetName().Version.ToString());
AddOSInformation();
AddThreadPoolInformation();
}
public void Reboot(int waitTime)
{
_logger.LogInformation("Reboot initiated.");
Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(waitTime));
Process.Start("shutdown", " -r now");
}, CancellationToken.None);
}
public void OnServicesInitialized()
{
ServicesInitialized?.Invoke(this, EventArgs.Empty);
_logger.LogInformation("Service startup completed.");
}
public void OnConfigurationLoaded()
{
ConfigurationLoaded?.Invoke(this, EventArgs.Empty);
_logger.LogInformation("Configuration loaded.");
}
public void OnStartupCompleted()
{
_systemStatusService.Set("startup.duration", DateTime.Now - _creationTimestamp);
PublishBootedNotification();
StartupCompleted?.Invoke(this, EventArgs.Empty);
_logger.LogInformation("Startup completed.");
}
private void PublishBootedNotification()
{
;
}
private void AddOSInformation()
{
_systemStatusService.Set("os.description", RuntimeInformation.OSDescription);
_systemStatusService.Set("os.architecture", RuntimeInformation.OSArchitecture);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_systemStatusService.Set("os.platform", "linux");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_systemStatusService.Set("os.platform", "windows");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
_systemStatusService.Set("os.platform", "osx");
}
}
private void AddThreadPoolInformation()
{
_systemStatusService.Set("thread_pool.max_worker_threads", () =>
{
ThreadPool.GetMaxThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.max_completion_port_threads", () =>
{
ThreadPool.GetMaxThreads(out _, out var x);
return x;
});
_systemStatusService.Set("thread_pool.min_worker_threads", () =>
{
ThreadPool.GetMinThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.min_completion_port_threads", () =>
{
ThreadPool.GetMinThreads(out _, out var x);
return x;
});
_systemStatusService.Set("thread_pool.available_worker_threads", () =>
{
ThreadPool.GetAvailableThreads(out var x, out _);
return x;
});
_systemStatusService.Set("thread_pool.available_completion_port_threads", () =>
{
ThreadPool.GetAvailableThreads(out _, out var x);
return x;
});
}
}
}
...@@ -92,8 +92,9 @@ ...@@ -92,8 +92,9 @@
<PackageReference Include="MQTTnet.AspNetCore" Version="3.0.2" /> <PackageReference Include="MQTTnet.AspNetCore" Version="3.0.2" />
<PackageReference Include="MQTTnet.Extensions.Rpc" Version="3.0.2" /> <PackageReference Include="MQTTnet.Extensions.Rpc" Version="3.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.4" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.4" />
<PackageReference Include="NSwag.AspNetCore" Version="12.3.1" /> <PackageReference Include="NSwag.AspNetCore" Version="13.0.2" />
<PackageReference Include="QuartzHostedService" Version="0.0.5" /> <PackageReference Include="QuartzHostedService" Version="0.0.5" />
<PackageReference Include="Quartzmin" Version="1.0.3" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" /> <PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
</ItemGroup> </ItemGroup>
<ProjectExtensions> <ProjectExtensions>
...@@ -107,6 +108,9 @@ ...@@ -107,6 +108,9 @@
<None Remove="$(SpaRoot)**" /> <None Remove="$(SpaRoot)**" />
<None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" /> <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Jobs\" />
</ItemGroup>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') "> <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed --> <!-- Ensure Node.js is installed -->
......
...@@ -11,12 +11,12 @@ namespace IoTSharp.MQTT ...@@ -11,12 +11,12 @@ namespace IoTSharp.MQTT
public class MqttTopicImporter public class MqttTopicImporter
{ {
private readonly MqttImportTopicParameters _parameters; private readonly MqttImportTopicParameters _parameters;
private readonly MqttEventsHandler _mqttService; private readonly MQTTService _mqttService;
private readonly ILogger _logger; private readonly ILogger _logger;
private IManagedMqttClient _mqttClient; private IManagedMqttClient _mqttClient;
public MqttTopicImporter(MqttImportTopicParameters parameters, MqttEventsHandler mqttService, ILogger logger) public MqttTopicImporter(MqttImportTopicParameters parameters, MQTTService mqttService, ILogger logger)
{ {
_parameters = parameters ?? throw new ArgumentNullException(nameof(parameters)); _parameters = parameters ?? throw new ArgumentNullException(nameof(parameters));
_mqttService = mqttService ?? throw new ArgumentNullException(nameof(mqttService)); _mqttService = mqttService ?? throw new ArgumentNullException(nameof(mqttService));
......
...@@ -20,9 +20,9 @@ using System.Threading.Tasks; ...@@ -20,9 +20,9 @@ using System.Threading.Tasks;
namespace IoTSharp.Services namespace IoTSharp.Services
{ {
public class MqttEventsHandler public class MQTTService
{ {
readonly ILogger<MqttEventsHandler> _logger; readonly ILogger<MQTTService> _logger;
readonly ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
readonly IMqttServerEx _serverEx; readonly IMqttServerEx _serverEx;
private readonly BlockingCollection<MqttApplicationMessageReceivedEventArgs> _incomingMessages = new BlockingCollection<MqttApplicationMessageReceivedEventArgs>(); private readonly BlockingCollection<MqttApplicationMessageReceivedEventArgs> _incomingMessages = new BlockingCollection<MqttApplicationMessageReceivedEventArgs>();
...@@ -31,16 +31,13 @@ namespace IoTSharp.Services ...@@ -31,16 +31,13 @@ namespace IoTSharp.Services
private readonly OperationsPerSecondCounter _inboundCounter; private readonly OperationsPerSecondCounter _inboundCounter;
private readonly OperationsPerSecondCounter _outboundCounter; private readonly OperationsPerSecondCounter _outboundCounter;
private readonly SystemStatusHandler _systemStatusHandler; public MQTTService(ILogger<MQTTService> logger, ApplicationDbContext dbContext, IMqttServerEx serverEx, DiagnosticsService diagnosticsService,
public MqttEventsHandler(ILogger<MqttEventsHandler> logger, ApplicationDbContext dbContext, IMqttServerEx serverEx, DiagnosticsService diagnosticsService, RuntimeStatusHandler systemStatusService
RuntimeStatusHandler systemStatusService,
SystemStatusHandler systemStatusHandler
) )
{ {
_logger = logger; _logger = logger;
_dbContext = dbContext; _dbContext = dbContext;
_serverEx = serverEx; _serverEx = serverEx;
_systemStatusHandler = systemStatusHandler;
_inboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.inbound_rate"); _inboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.inbound_rate");
_outboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.outbound_rate"); _outboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.outbound_rate");
...@@ -295,7 +292,7 @@ namespace IoTSharp.Services ...@@ -295,7 +292,7 @@ namespace IoTSharp.Services
{ {
if (e.TopicFilter.Topic.StartsWith("$SYS/broker/version")) if (e.TopicFilter.Topic.StartsWith("$SYS/broker/version"))
{ {
var mename = typeof(MqttEventsHandler).Assembly.GetName(); var mename = typeof(MQTTService).Assembly.GetName();
var mqttnet = typeof(MqttServerClientSubscribedTopicEventArgs).Assembly.GetName(); var mqttnet = typeof(MqttServerClientSubscribedTopicEventArgs).Assembly.GetName();
Task.Run(() => _serverEx.PublishAsync("$SYS/broker/version", $"{mename.Name}V{mename.Version.ToString()},{mqttnet.Name}.{mqttnet.Version.ToString()}")); Task.Run(() => _serverEx.PublishAsync("$SYS/broker/version", $"{mename.Name}V{mename.Version.ToString()},{mqttnet.Name}.{mqttnet.Version.ToString()}"));
} }
......
...@@ -54,7 +54,7 @@ namespace IoTSharp.Services ...@@ -54,7 +54,7 @@ namespace IoTSharp.Services
_logger.LogInformation($"CONNECTED IsSessionPresent: {e.AuthenticateResult.IsSessionPresent } ResultCode: { e.AuthenticateResult.ResultCode}"); _logger.LogInformation($"CONNECTED IsSessionPresent: {e.AuthenticateResult.IsSessionPresent } ResultCode: { e.AuthenticateResult.ResultCode}");
} }
Dictionary<string, Device> Devices => MqttEventsHandler.Devices; Dictionary<string, Device> Devices => MQTTService.Devices;
private void Mqtt_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e) private void Mqtt_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
{ {
......
...@@ -23,6 +23,9 @@ using MQTTnet.AspNetCore; ...@@ -23,6 +23,9 @@ using MQTTnet.AspNetCore;
using MQTTnet.AspNetCoreEx; using MQTTnet.AspNetCoreEx;
using MQTTnet.Client; using MQTTnet.Client;
using NSwag.AspNetCore; using NSwag.AspNetCore;
using Quartz;
using QuartzHostedService;
using Quartzmin;
using System; using System;
using System.Configuration; using System.Configuration;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
...@@ -99,12 +102,13 @@ namespace IoTSharp ...@@ -99,12 +102,13 @@ namespace IoTSharp
services.AddSingleton<DiagnosticsService>(); services.AddSingleton<DiagnosticsService>();
services.AddSingleton<RetainedMessageHandler>(); services.AddSingleton<RetainedMessageHandler>();
services.AddSingleton<RuntimeStatusHandler>(); services.AddSingleton<RuntimeStatusHandler>();
services.AddSingleton<SystemStatusHandler>();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ {
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
...@@ -116,12 +120,13 @@ namespace IoTSharp ...@@ -116,12 +120,13 @@ namespace IoTSharp
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts(); app.UseHsts();
} }
app.UseAuthentication(); app.UseAuthentication();
app.UseSwagger(); app.UseSwagger();
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseIotSharpMqttServer(); app.UseIotSharpMqttServer();
// serviceProvider.GetRequiredService<MqttService>().Start();
app.UseForwardedHeaders(new ForwardedHeadersOptions app.UseForwardedHeaders(new ForwardedHeadersOptions
{ {
...@@ -142,7 +147,7 @@ namespace IoTSharp ...@@ -142,7 +147,7 @@ namespace IoTSharp
name: "default", name: "default",
template: "{controller}/{action=Index}/{id?}"); template: "{controller}/{action=Index}/{id?}");
}); });
app.UseSpa(spa => app.UseSpa(spa =>
{ {
// To learn more about options for serving an Angular SPA from ASP.NET Core, // To learn more about options for serving an Angular SPA from ASP.NET Core,
...@@ -155,7 +160,7 @@ namespace IoTSharp ...@@ -155,7 +160,7 @@ namespace IoTSharp
spa.UseVueCliServer(npmScript: "dev"); spa.UseVueCliServer(npmScript: "dev");
} }
}); });
app.UseIotSharpSelfCollecting();
} }
} }
} }
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueFileSectionHandler" />
</configSections>
<quartz>
<add key="quartz.plugin.recentHistory.type" value="Quartz.Plugins.RecentHistory.ExecutionHistoryPlugin, Quartz.Plugins.RecentHistory" />
<add key="quartz.plugin.recentHistory.storeType" value="Quartz.Plugins.RecentHistory.Impl.InProcExecutionHistoryStore, Quartz.Plugins.RecentHistory" />
</quartz>
</configuration>
\ No newline at end of file
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
"DataBase": "npgsql", "DataBase": "npgsql",
"ConnectionStrings": { "ConnectionStrings": {
"mssql": "Server=localhost;Database=IoTSharp;Trusted_Connection=True;MultipleActiveResultSets=true", "mssql": "Server=localhost;Database=IoTSharp;Trusted_Connection=True;MultipleActiveResultSets=true",
"npgsql": "Server=localhost;Database=IoTSharp;Username=postgres;Password=postgres;", "npgsql": "Server=localhost;Database=IoTSharp;Username=postgres;Password=future;",
"sqlite": "Data Source=:memory:" "sqlite": "Data Source=:memory:"
}, },
"JwtKey": "kissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissme", "JwtKey": "kissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissmekissme",
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册