系统设置明文化+仪表盘apiKey数据库化+日志分类+安装脚本防闪退

main
haoliang 24 hours ago
parent f703f92098
commit 3f1e998f8e

@ -157,10 +157,9 @@ function getDisplayValue(row: SysConfig): string {
return String(row.configValue) return String(row.configValue)
} }
// //
function isSensitive(key: string): boolean { function isSensitive(_key: string): boolean {
const k = (key || '').toLowerCase() return false
return k === 'api_token' || k === 'collector_api_key' || k.includes('token') || k.includes('key') || k.includes('secret') || k.includes('password')
} }
// ===== Tab1: ===== // ===== Tab1: =====

@ -1,12 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<log4net> <log4net>
<!-- 控制台输出(调试用) -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout> </layout>
</appender> </appender>
<!-- 运行日志INFO及以上含INFO/WARN/ERROR/FATAL -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\\collector.log" /> <file value="logs\collector.log" />
<appendToFile value="true" /> <appendToFile value="true" />
<rollingStyle value="Date" /> <rollingStyle value="Date" />
<datePattern value="yyyyMMdd" /> <datePattern value="yyyyMMdd" />
@ -16,9 +19,25 @@
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout> </layout>
</appender> </appender>
<!-- 错误日志仅ERROR和FATAL -->
<appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\collector_error.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="10MB" />
<threshold value="ERROR" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root> <root>
<level value="INFO" /> <level value="INFO" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" /> <appender-ref ref="RollingFileAppender" />
<appender-ref ref="ErrorFileAppender" />
</root> </root>
</log4net> </log4net>

@ -10,7 +10,7 @@ param(
[string]$Method = "installutil" [string]$Method = "installutil"
) )
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Continue"
$serviceName = "CncCollector" $serviceName = "CncCollector"
$installDir = "C:\CncCollector" $installDir = "C:\CncCollector"
$projectDir = Split-Path -Parent $PSScriptRoot $projectDir = Split-Path -Parent $PSScriptRoot
@ -18,7 +18,7 @@ $binDir = Join-Path $projectDir "bin"
$exePath = Join-Path $binDir "CncCollector.exe" $exePath = Join-Path $binDir "CncCollector.exe"
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
Write-Host " CNC 机床数据采集服务 - 安装脚本 v2.0" -ForegroundColor Cyan Write-Host " CNC 机床数据采集服务 - 安装脚本 v2.1" -ForegroundColor Cyan
Write-Host " 安装方式: $Method" -ForegroundColor Cyan Write-Host " 安装方式: $Method" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
@ -26,6 +26,8 @@ Write-Host "================================================" -ForegroundColor C
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) { if (-not $isAdmin) {
Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 1 exit 1
} }
@ -34,6 +36,8 @@ if (-not (Test-Path $exePath)) {
Write-Host "[错误] 找不到 CncCollector.exe请先编译项目。" -ForegroundColor Red Write-Host "[错误] 找不到 CncCollector.exe请先编译项目。" -ForegroundColor Red
Write-Host " 预期路径: $exePath" -ForegroundColor Yellow Write-Host " 预期路径: $exePath" -ForegroundColor Yellow
Write-Host " 编译命令: dotnet build src\CncCollector\CncCollector.csproj -c Debug" -ForegroundColor Yellow Write-Host " 编译命令: dotnet build src\CncCollector\CncCollector.csproj -c Debug" -ForegroundColor Yellow
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 1 exit 1
} }
@ -133,6 +137,8 @@ switch ($Method) {
} else { } else {
Write-Host " [错误] 未找到 NSSM请先安装 NSSM 或使用其他安装方式。" -ForegroundColor Red Write-Host " [错误] 未找到 NSSM请先安装 NSSM 或使用其他安装方式。" -ForegroundColor Red
Write-Host " 替代方案: .\install.ps1 -Method installutil" -ForegroundColor Yellow Write-Host " 替代方案: .\install.ps1 -Method installutil" -ForegroundColor Yellow
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 1 exit 1
} }
} }
@ -165,14 +171,23 @@ if ($svc -and $svc.Status -eq 'Running') {
# 尝试调用管理API验证 # 尝试调用管理API验证
try { try {
$response = Invoke-WebRequest -Uri "http://localhost:5800/api/collector/status" -Headers @{ "X-Api-Key" = "collector_api_key_2026" } -TimeoutSec 5 -ErrorAction Stop # 从collector.json读取apiKey
$configFile = Join-Path $installDir "collector.json"
$apiKey = "collector_api_key_2026"
if (Test-Path $configFile) {
$configJson = Get-Content $configFile -Raw | ConvertFrom-Json
if ($configJson.apiKey) { $apiKey = $configJson.apiKey }
}
$response = Invoke-WebRequest -Uri "http://localhost:5800/api/collector/status" -Headers @{ "X-Api-Key" = $apiKey } -TimeoutSec 5 -ErrorAction Stop
Write-Host " API状态: $($response.StatusCode) - 服务运行正常" -ForegroundColor Green Write-Host " API状态: $($response.StatusCode) - 服务运行正常" -ForegroundColor Green
} catch { } catch {
Write-Host " API状态: 未响应(可能正在初始化)" -ForegroundColor Yellow Write-Host " API状态: 未响应(可能正在初始化)" -ForegroundColor Yellow
} }
} else { } else {
Write-Host "`n[警告] 服务已安装但未能启动,请检查配置和日志。" -ForegroundColor Yellow Write-Host "`n[警告] 服务已安装但未能启动,请检查配置和日志。" -ForegroundColor Yellow
Write-Host " 日志目录: $installDir" -ForegroundColor Gray Write-Host " 日志目录: $installDir\logs\" -ForegroundColor Gray
Write-Host " 运行日志: collector.log" -ForegroundColor Gray
Write-Host " 错误日志: collector_error.log" -ForegroundColor Gray
Write-Host " 查看事件日志: Get-EventLog -LogName Application -Source CncCollector -Newest 10" -ForegroundColor Gray Write-Host " 查看事件日志: Get-EventLog -LogName Application -Source CncCollector -Newest 10" -ForegroundColor Gray
} }
@ -182,3 +197,6 @@ Write-Host " 停止: Stop-Service $serviceName" -ForegroundColor Gray
Write-Host " 状态: Get-Service $serviceName" -ForegroundColor Gray Write-Host " 状态: Get-Service $serviceName" -ForegroundColor Gray
Write-Host " 卸载: .\uninstall.ps1" -ForegroundColor Gray Write-Host " 卸载: .\uninstall.ps1" -ForegroundColor Gray
Write-Host " 控制台调试: CncCollector.exe --console" -ForegroundColor Gray Write-Host " 控制台调试: CncCollector.exe --console" -ForegroundColor Gray
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host

@ -2,24 +2,28 @@
# 需要管理员权限运行 # 需要管理员权限运行
# 用法: .\uninstall.ps1 # 用法: .\uninstall.ps1
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Continue"
$serviceName = "CncCollector" $serviceName = "CncCollector"
$installDir = "C:\CncCollector" $installDir = "C:\CncCollector"
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
Write-Host " CNC 机床数据采集服务 - 卸载脚本 v2.0" -ForegroundColor Cyan Write-Host " CNC 机床数据采集服务 - 卸载脚本 v2.1" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
# 检查管理员权限 # 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) { if (-not $isAdmin) {
Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 1 exit 1
} }
$svc = Get-Service -Name $serviceName -ErrorAction SilentlyContinue $svc = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if (-not $svc) { if (-not $svc) {
Write-Host "[提示] 服务未安装,无需卸载。" -ForegroundColor Yellow Write-Host "[提示] 服务未安装,无需卸载。" -ForegroundColor Yellow
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 0 exit 0
} }
@ -105,5 +109,7 @@ if (-not $check) {
} else { } else {
Write-Host "[错误] 服务删除失败,可能需要重启后再试。" -ForegroundColor Red Write-Host "[错误] 服务删除失败,可能需要重启后再试。" -ForegroundColor Red
Write-Host " 手动删除: sc.exe delete $serviceName" -ForegroundColor Yellow Write-Host " 手动删除: sc.exe delete $serviceName" -ForegroundColor Yellow
exit 1
} }
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host

@ -5,6 +5,7 @@ using System.Text;
using System.Web.Http; using System.Web.Http;
using CncModels.Dto; using CncModels.Dto;
using CncModels.Dto.Dashboard; using CncModels.Dto.Dashboard;
using CncRepository.Interface;
using CncService.Interface; using CncService.Interface;
using CncWebApi.Infrastructure; using CncWebApi.Infrastructure;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -19,14 +20,16 @@ namespace CncWebApi.Controllers
public class DashboardController : ApiController public class DashboardController : ApiController
{ {
private readonly IDashboardService _dashboardService; private readonly IDashboardService _dashboardService;
private readonly ISysConfigRepository _sysConfigRepository;
private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
/// <summary> /// <summary>
/// 构造函数 /// 构造函数
/// </summary> /// </summary>
public DashboardController(IDashboardService dashboardService) public DashboardController(IDashboardService dashboardService, ISysConfigRepository sysConfigRepository)
{ {
_dashboardService = dashboardService; _dashboardService = dashboardService;
_sysConfigRepository = sysConfigRepository;
} }
/// <summary> /// <summary>
@ -198,8 +201,12 @@ namespace CncWebApi.Controllers
{ {
try try
{ {
// 从数据库读取采集服务API Key
var apiKeyConfig = _sysConfigRepository.GetByKey("collector_api_key");
string apiKey = apiKeyConfig?.ConfigValue ?? "collector_api_key_2026";
var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:5800{path}"); var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:5800{path}");
request.Headers.Add("X-Api-Key", "collector_api_key_2026"); request.Headers.Add("X-Api-Key", apiKey);
var response = _httpClient.SendAsync(request).Result; var response = _httpClient.SendAsync(request).Result;
var body = response.Content.ReadAsStringAsync().Result; var body = response.Content.ReadAsStringAsync().Result;
return Ok(ApiResponse<object>.Success(new { forwarded = true, collectorResponse = JsonConvert.DeserializeObject(body) })); return Ok(ApiResponse<object>.Success(new { forwarded = true, collectorResponse = JsonConvert.DeserializeObject(body) }));

@ -35,7 +35,8 @@ namespace CncWebApi.Infrastructure
ResolveAuthService()); ResolveAuthService());
if (serviceType == typeof(Controllers.DashboardController)) if (serviceType == typeof(Controllers.DashboardController))
return new Controllers.DashboardController( return new Controllers.DashboardController(
ResolveDashboardService()); ResolveDashboardService(),
ResolveSysConfigRepository());
if (serviceType == typeof(Controllers.MachineController)) if (serviceType == typeof(Controllers.MachineController))
return new Controllers.MachineController( return new Controllers.MachineController(
ResolveMachineService()); ResolveMachineService());
@ -203,6 +204,11 @@ namespace CncWebApi.Infrastructure
new CncRepository.Impl.Log.CollectCycleRepository(_logConn)); new CncRepository.Impl.Log.CollectCycleRepository(_logConn));
} }
private ISysConfigRepository ResolveSysConfigRepository()
{
return new CncRepository.Impl.SysConfigRepository(_businessConn);
}
private IReplayService ResolveReplayService() private IReplayService ResolveReplayService()
{ {
return new CncService.Impl.ReplayService(_businessConn, _logConn); return new CncService.Impl.ReplayService(_businessConn, _logConn);

@ -82,7 +82,7 @@ namespace CncWebApi.Tests
public static WorkerController CreateWorkerController() => new WorkerController(CreateWorkerService()); public static WorkerController CreateWorkerController() => new WorkerController(CreateWorkerService());
/// <summary>创建DashboardController</summary> /// <summary>创建DashboardController</summary>
public static DashboardController CreateDashboardController() => new DashboardController(CreateDashboardService()); public static DashboardController CreateDashboardController() => new DashboardController(CreateDashboardService(), SysConfigRepo());
/// <summary>创建SettingsController系统配置+车间管理)</summary> /// <summary>创建SettingsController系统配置+车间管理)</summary>
public static SettingsController CreateSettingsController() => new SettingsController(SysConfigRepo(), CreateWorkshopService()); public static SettingsController CreateSettingsController() => new SettingsController(SysConfigRepo(), CreateWorkshopService());

Loading…
Cancel
Save