Browse Source

更新代码

master
root 2 days ago
parent
commit
89926718f2
  1. 12
      CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs
  2. 2
      CoreAgent.Domain/Interfaces/Network/INetworkConfigCopier.cs
  3. 2
      CoreAgent.Domain/Interfaces/Network/INetworkIPEndPointManager.cs
  4. 41
      CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs
  5. 27
      CoreAgent.Domain/Models/Network/NetworkConfigType.cs
  6. 2
      CoreAgent.Domain/Models/Network/NetworkIPEndPoints.cs
  7. 14
      CoreAgent.Domain/Models/Network/NetworkInterfaceOperationResult.cs
  8. 72
      CoreAgent.Domain/Models/Network/NetworkStatusModels.cs
  9. 40
      CoreAgent.Domain/Models/System/AppSettings.cs
  10. 31
      CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs
  11. 26
      CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs
  12. 24
      CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs
  13. 4
      CoreAgent.Infrastructure/Services/Network/NetworkConfigCopier.cs
  14. 2
      CoreAgent.Infrastructure/Services/Network/NetworkIPEndPointManager.cs
  15. 26
      CoreAgent.Infrastructure/Services/Network/NetworkInterfaceManager.cs
  16. 337
      CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs

12
CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs

@ -25,6 +25,11 @@ public interface ICellularNetworkContext
/// </summary> /// </summary>
INetworkIPEndPointManager NetworkIPEndPointManager { get; } INetworkIPEndPointManager NetworkIPEndPointManager { get; }
/// <summary>
/// 当前网络配置类型
/// </summary>
NetworkConfigType CurrentConfigType { get; }
#endregion #endregion
#region 生命周期管理 #region 生命周期管理
@ -65,6 +70,12 @@ public interface ICellularNetworkContext
/// </summary> /// </summary>
AppSettings GetAppSettings(); AppSettings GetAppSettings();
/// <summary>
/// 更新网络配置类型
/// </summary>
/// <param name="configType">网络配置类型</param>
void UpdateNetworkConfigType(NetworkConfigType configType);
#endregion #endregion
#region 命令管理 #region 命令管理
@ -91,6 +102,5 @@ public interface ICellularNetworkContext
/// </summary> /// </summary>
/// <returns>网络状态</returns> /// <returns>网络状态</returns>
CellularNetworkState GetNetworkState(); CellularNetworkState GetNetworkState();
#endregion #endregion
} }

2
CoreAgent.Domain/Interfaces/Network/INetworkConfigCopier.cs

@ -22,5 +22,5 @@ public interface INetworkConfigCopier
/// </summary> /// </summary>
/// <param name="networkConfig">网络配置</param> /// <param name="networkConfig">网络配置</param>
/// <returns>(EndPoints: IP 端点信息集合, HasAnyEndPoint: 是否成功获取到任何端点信息)</returns> /// <returns>(EndPoints: IP 端点信息集合, HasAnyEndPoint: 是否成功获取到任何端点信息)</returns>
Task<(NetworkIPEndPoints EndPoints, bool HasAnyEndPoint)> GetComAddrInfoAsync(NetworkConfiguration networkConfig); Task<(NetworkIPEndPointCollection EndPoints, bool HasAnyEndPoint)> GetComAddrInfoAsync(NetworkConfiguration networkConfig);
} }

2
CoreAgent.Domain/Interfaces/Network/INetworkIPEndPointManager.cs

@ -11,7 +11,7 @@ public interface INetworkIPEndPointManager
/// 更新 IP 端点信息 /// 更新 IP 端点信息
/// </summary> /// </summary>
/// <param name="endPoints">IP 端点信息集合</param> /// <param name="endPoints">IP 端点信息集合</param>
void UpdateEndPoints(NetworkIPEndPoints endPoints); void UpdateEndPoints(NetworkIPEndPointCollection endPoints);
/// <summary> /// <summary>
/// 获取 RAN 端点信息 /// 获取 RAN 端点信息

41
CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs

@ -0,0 +1,41 @@
using CoreAgent.Domain.Models.Network;
namespace CoreAgent.Domain.Interfaces.Network;
/// <summary>
/// 网络状态监控接口
/// </summary>
public interface INetworkStatusMonitor
{
/// <summary>
/// 检查所有网络端点的状态
/// </summary>
/// <param name="endPoints">网络端点信息</param>
/// <param name="configType">网络配置类型</param>
/// <returns>检查结果</returns>
public Task<NetworkStatusCheckResult> CheckAllEndPointsStatusAsync(
NetworkIPEndPointCollection endPoints,
NetworkConfigType configType,
int? timeoutSeconds = null);
/// <summary>
/// 检查 RAN 端点状态
/// </summary>
/// <param name="ranEndPoint">RAN 端点信息</param>
/// <returns>RAN 端点状态</returns>
Task<EndPointStatusResult> CheckRanStatusAsync(RanIPEndPoint ranEndPoint);
/// <summary>
/// 检查 IMS 端点状态
/// </summary>
/// <param name="imsEndPoints">IMS 端点信息列表</param>
/// <returns>IMS 端点状态列表</returns>
Task<List<EndPointStatusResult>> CheckImsStatusAsync(List<ImsIPEndPoint> imsEndPoints);
/// <summary>
/// 检查 CN 端点状态
/// </summary>
/// <param name="cnEndPoints">CN 端点信息列表</param>
/// <returns>CN 端点状态列表</returns>
Task<List<EndPointStatusResult>> CheckCnStatusAsync(List<CnIPEndPoint> cnEndPoints);
}

27
CoreAgent.Domain/Models/Network/NetworkConfigType.cs

@ -0,0 +1,27 @@
namespace CoreAgent.Domain.Models.Network;
/// <summary>
/// 网络配置类型
/// </summary>
public enum NetworkConfigType
{
/// <summary>
/// 无配置
/// </summary>
None = 0,
/// <summary>
/// 同时包含RAG和Core配置
/// </summary>
BothRagAndCore,
/// <summary>
/// 仅包含RAG配置
/// </summary>
RagOnly,
/// <summary>
/// 仅包含Core配置
/// </summary>
CoreOnly
}

2
CoreAgent.Domain/Models/Network/NetworkIPEndPoints.cs

@ -3,7 +3,7 @@ namespace CoreAgent.Domain.Models.Network;
/// <summary> /// <summary>
/// 网络 IP 端点集合 /// 网络 IP 端点集合
/// </summary> /// </summary>
public class NetworkIPEndPoints public class NetworkIPEndPointCollection
{ {
/// <summary> /// <summary>
/// IMS 网络 IP 端点列表 /// IMS 网络 IP 端点列表

14
CoreAgent.Domain/Models/Network/NetworkInterfaceOperationResult.cs

@ -15,20 +15,28 @@ public class NetworkInterfaceOperationResult
/// </summary> /// </summary>
public string ErrorMessage { get; } public string ErrorMessage { get; }
private NetworkInterfaceOperationResult(bool isSuccess, string errorMessage = null) /// <summary>
/// 网络配置类型
/// </summary>
public NetworkConfigType ConfigType { get; }
private NetworkInterfaceOperationResult(bool isSuccess, string errorMessage = null, NetworkConfigType configType = NetworkConfigType.None)
{ {
IsSuccess = isSuccess; IsSuccess = isSuccess;
ErrorMessage = errorMessage; ErrorMessage = errorMessage;
ConfigType = configType;
} }
/// <summary> /// <summary>
/// 创建成功结果 /// 创建成功结果
/// </summary> /// </summary>
public static NetworkInterfaceOperationResult Success() => new(true); /// <param name="configType">网络配置类型</param>
public static NetworkInterfaceOperationResult Success(NetworkConfigType configType = NetworkConfigType.None) => new(true, null, configType);
/// <summary> /// <summary>
/// 创建失败结果 /// 创建失败结果
/// </summary> /// </summary>
/// <param name="errorMessage">错误信息</param> /// <param name="errorMessage">错误信息</param>
public static NetworkInterfaceOperationResult Failure(string errorMessage) => new(false, errorMessage); /// <param name="configType">网络配置类型</param>
public static NetworkInterfaceOperationResult Failure(string errorMessage, NetworkConfigType configType = NetworkConfigType.None) => new(false, errorMessage, configType);
} }

72
CoreAgent.Domain/Models/Network/NetworkStatusModels.cs

@ -0,0 +1,72 @@
using CoreAgent.Domain.Models.Network;
namespace CoreAgent.Domain.Models.Network;
/// <summary>
/// 端点状态检查结果
/// </summary>
public class EndPointStatusResult
{
/// <summary>
/// 通信地址
/// </summary>
public string ComAddr { get; set; }
/// <summary>
/// 是否成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// 网络协议类型
/// </summary>
public NetworkProtocolType NetworkProtocolType { get; set; }
}
/// <summary>
/// 网络状态检查结果
/// </summary>
public class NetworkStatusCheckResult
{
/// <summary>
/// 是否成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string[] ErrorMessage { get; set; }
}
/// <summary>
/// 网络协议类型
/// </summary>
public enum NetworkProtocolType
{
/// <summary>
/// 未指定
/// </summary>
None = 0,
/// <summary>
/// RAN 协议
/// </summary>
Ran = 1,
/// <summary>
/// IMS 协议
/// </summary>
Ims = 2,
/// <summary>
/// CN 协议
/// </summary>
Cn = 3
}

40
CoreAgent.Domain/Models/System/AppSettings.cs

@ -24,4 +24,44 @@ public class AppSettings
/// WebSocket JavaScript文件路径 /// WebSocket JavaScript文件路径
/// </summary> /// </summary>
public string WebSocketJsPath { get; set; } = "/root/enb/doc/ws.js"; public string WebSocketJsPath { get; set; } = "/root/enb/doc/ws.js";
/// <summary>
/// WebSocket 命令配置
/// </summary>
public WebSocketCommandSettings WebSocketCommands { get; set; } = new();
/// <summary>
/// 网络状态检查超时时间(秒)
/// </summary>
public int NetworkStatusCheckTimeout { get; set; } = 30;
}
/// <summary>
/// WebSocket 命令配置
/// </summary>
public class WebSocketCommandSettings
{
/// <summary>
/// 状态检查命令
/// </summary>
public WebSocketCommand Stats { get; set; } = new()
{
Message = "stats"
};
}
/// <summary>
/// WebSocket 命令
/// </summary>
public class WebSocketCommand
{
/// <summary>
/// 消息类型
/// </summary>
public string Message { get; set; } = string.Empty;
/// <summary>
/// 转换为 JSON 字符串
/// </summary>
public string ToJson() => $"{{\"message\":\"{Message}\"}}";
} }

31
CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs

@ -20,6 +20,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
private bool _isDisposed; private bool _isDisposed;
private bool _isInitialized; private bool _isInitialized;
private readonly INetworkIPEndPointManager _networkIPEndPointManager; private readonly INetworkIPEndPointManager _networkIPEndPointManager;
private NetworkConfigType _currentConfigType;
/// <summary> /// <summary>
/// 获取取消令牌源 /// 获取取消令牌源
@ -36,6 +37,11 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
/// </summary> /// </summary>
public INetworkIPEndPointManager NetworkIPEndPointManager => _networkIPEndPointManager; public INetworkIPEndPointManager NetworkIPEndPointManager => _networkIPEndPointManager;
/// <summary>
/// 当前网络配置类型
/// </summary>
public NetworkConfigType CurrentConfigType => _currentConfigType;
public CellularNetworkContext( public CellularNetworkContext(
IOptions<NetworkCommandConfig> networkCommandConfig, IOptions<NetworkCommandConfig> networkCommandConfig,
IOptions<AppSettings> appSettings, IOptions<AppSettings> appSettings,
@ -47,6 +53,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
_networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig)); _networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig));
_appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings)); _appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings));
_networkIPEndPointManager = networkIPEndPointManager ?? throw new ArgumentNullException(nameof(networkIPEndPointManager)); _networkIPEndPointManager = networkIPEndPointManager ?? throw new ArgumentNullException(nameof(networkIPEndPointManager));
_currentConfigType = NetworkConfigType.None;
} }
/// <summary> /// <summary>
@ -75,10 +82,33 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
_networkIPEndPointManager.Clear(); _networkIPEndPointManager.Clear();
_neConfigKey = neConfigKey; _neConfigKey = neConfigKey;
_networkState = new CellularNetworkState(_neConfigKey); _networkState = new CellularNetworkState(_neConfigKey);
_currentConfigType = NetworkConfigType.None;
_isInitialized = true; _isInitialized = true;
} }
} }
/// <summary>
/// 更新网络配置类型
/// </summary>
/// <param name="configType">网络配置类型</param>
public void UpdateNetworkConfigType(NetworkConfigType configType)
{
if (_isDisposed)
{
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
throw new InvalidOperationException("上下文未初始化");
}
lock (_lock)
{
_currentConfigType = configType;
}
}
/// <summary> /// <summary>
/// 获取网络命令配置 /// 获取网络命令配置
/// </summary> /// </summary>
@ -192,6 +222,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
_isInitialized = false; _isInitialized = false;
_networkState = new CellularNetworkState(string.Empty); _networkState = new CellularNetworkState(string.Empty);
_networkIPEndPointManager.Clear(); _networkIPEndPointManager.Clear();
_currentConfigType = NetworkConfigType.None;
} }
} }

26
CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs

@ -1,4 +1,3 @@
using CoreAgent.Domain.Interfaces; using CoreAgent.Domain.Interfaces;
using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Interfaces.System.Command; using CoreAgent.Domain.Interfaces.System.Command;
@ -17,30 +16,43 @@ namespace CoreAgent.Infrastructure.Extensions.ServiceCollection;
public static class CommandServiceExtensions public static class CommandServiceExtensions
{ {
/// <summary> /// <summary>
/// 添加命令策略服务 /// 添加命令相关的自定义服务
/// </summary> /// </summary>
/// <remarks>
/// 此方法注册以下服务:
/// 1. 网络IP端点管理器(单例)
/// 2. 蜂窝网络上下文(单例)
/// 3. 系统命令执行器工厂(单例)
/// 4. 系统命令执行器(瞬时)
/// 5. 网络配置仓储(作用域)
/// 6. 网络配置服务(作用域)
/// 7. 网络配置复制器(作用域)
/// 8. 网络接口管理器(作用域)
/// 9. 网络状态监控器(作用域)
/// 10. 蜂窝网络服务(作用域)
/// </remarks>
/// <param name="services">服务集合</param> /// <param name="services">服务集合</param>
/// <returns>服务集合</returns> /// <returns>服务集合</returns>
public static IServiceCollection AddCommandCustomService(this IServiceCollection services) public static IServiceCollection AddCommandCustomService(this IServiceCollection services)
{ {
// 注册单例服务
services.AddSingleton<INetworkIPEndPointManager, NetworkIPEndPointManager>(); services.AddSingleton<INetworkIPEndPointManager, NetworkIPEndPointManager>();
services.AddSingleton<ICellularNetworkContext, CellularNetworkContext>(); services.AddSingleton<ICellularNetworkContext, CellularNetworkContext>();
// 注册命令执行器工厂
services.AddSingleton<ISystemCommandExecutorFactory, SystemCommandExecutorFactory>(); services.AddSingleton<ISystemCommandExecutorFactory, SystemCommandExecutorFactory>();
// 注册命令执行器 // 注册命令执行器(瞬时)
services.AddTransient<ISystemCommandExecutor>(sp => services.AddTransient<ISystemCommandExecutor>(sp =>
{ {
var factory = sp.GetRequiredService<ISystemCommandExecutorFactory>(); var factory = sp.GetRequiredService<ISystemCommandExecutorFactory>();
return factory.CreateExecutor(); return factory.CreateExecutor();
}); });
// 注册网络配置器
// 注册作用域服务
services.AddScoped<INetworkConfigurationRepository, NetworkConfigurationRepository>(); services.AddScoped<INetworkConfigurationRepository, NetworkConfigurationRepository>();
// 注册网络配置器
services.AddScoped<INetworkConfigurationService, NetworkConfigurationService>(); services.AddScoped<INetworkConfigurationService, NetworkConfigurationService>();
services.AddScoped<INetworkConfigCopier, NetworkConfigCopier>(); services.AddScoped<INetworkConfigCopier, NetworkConfigCopier>();
services.AddScoped<INetworkInterfaceManager, NetworkInterfaceManager>(); services.AddScoped<INetworkInterfaceManager, NetworkInterfaceManager>();
// 注册网络服务 services.AddScoped<INetworkStatusMonitor, NetworkStatusMonitor>();
services.AddScoped<ICellularNetworkService, CellularNetworkService>(); services.AddScoped<ICellularNetworkService, CellularNetworkService>();
return services; return services;

24
CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

@ -22,6 +22,7 @@ public class CellularNetworkService : ICellularNetworkService
private readonly ICellularNetworkContext _context; private readonly ICellularNetworkContext _context;
private readonly INetworkConfigCopier _configCopier; private readonly INetworkConfigCopier _configCopier;
private readonly INetworkInterfaceManager _interfaceManager; private readonly INetworkInterfaceManager _interfaceManager;
private readonly INetworkStatusMonitor _statusMonitor;
private static readonly SemaphoreSlim _startLock = new(1, 1); private static readonly SemaphoreSlim _startLock = new(1, 1);
private const int LockTimeoutSeconds = 60; private const int LockTimeoutSeconds = 60;
@ -32,7 +33,8 @@ public class CellularNetworkService : ICellularNetworkService
INetworkConfigurationService configService, INetworkConfigurationService configService,
ICellularNetworkContext context, ICellularNetworkContext context,
INetworkConfigCopier configCopier, INetworkConfigCopier configCopier,
INetworkInterfaceManager interfaceManager) INetworkInterfaceManager interfaceManager,
INetworkStatusMonitor statusMonitor)
{ {
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
_commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor)); _commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor));
@ -40,6 +42,7 @@ public class CellularNetworkService : ICellularNetworkService
_context = context ?? throw new ArgumentNullException(nameof(context)); _context = context ?? throw new ArgumentNullException(nameof(context));
_configCopier = configCopier ?? throw new ArgumentNullException(nameof(configCopier)); _configCopier = configCopier ?? throw new ArgumentNullException(nameof(configCopier));
_interfaceManager = interfaceManager ?? throw new ArgumentNullException(nameof(interfaceManager)); _interfaceManager = interfaceManager ?? throw new ArgumentNullException(nameof(interfaceManager));
_statusMonitor = statusMonitor;
} }
/// <summary> /// <summary>
@ -240,10 +243,25 @@ public class CellularNetworkService : ICellularNetworkService
return CellularNetworkOperationResult.Failure(message); return CellularNetworkOperationResult.Failure(message);
} }
// 7. 更新状态 // 7. 更新网络配置类型
_context.UpdateNetworkConfigType(enableResult.ConfigType);
_logger.LogInformation("更新网络配置类型: {ConfigType}", enableResult.ConfigType);
// 8. 检查所有网络端点的连接状态
_logger.LogInformation("开始检查所有网络端点的连接状态");
var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, enableResult.ConfigType);
if (!statusCheckResult.IsSuccess)
{
var errorMessage = string.Join("; ", statusCheckResult.ErrorMessage);
_logger.LogWarning("网络端点状态检查未通过: {ErrorMessage}", errorMessage);
return CellularNetworkOperationResult.Failure($"网络端点状态检查失败: {errorMessage}");
}
_logger.LogInformation("网络端点状态检查完成,所有端点状态正常");
// 9. 更新状态
var state = _context.GetNetworkState(); var state = _context.GetNetworkState();
state.MarkAsStarted(); state.MarkAsStarted();
_logger.LogInformation("蜂窝网络配置 {ConfigKey} 启动成功", key); _logger.LogInformation("蜂窝网络配置 {ConfigKey} 启动成功,当前状态: {Status}", key, state.CurrentStatus);
return CellularNetworkOperationResult.Success(state.CurrentStatus); return CellularNetworkOperationResult.Success(state.CurrentStatus);
} }
} }

4
CoreAgent.Infrastructure/Services/Network/NetworkConfigCopier.cs

@ -205,9 +205,9 @@ public class NetworkConfigCopier : INetworkConfigCopier
/// </summary> /// </summary>
/// <param name="networkConfig">网络配置</param> /// <param name="networkConfig">网络配置</param>
/// <returns>(EndPoints: IP 端点信息集合, HasAnyEndPoint: 是否成功获取到任何端点信息)</returns> /// <returns>(EndPoints: IP 端点信息集合, HasAnyEndPoint: 是否成功获取到任何端点信息)</returns>
public async Task<(NetworkIPEndPoints EndPoints, bool HasAnyEndPoint)> GetComAddrInfoAsync(NetworkConfiguration networkConfig) public async Task<(NetworkIPEndPointCollection EndPoints, bool HasAnyEndPoint)> GetComAddrInfoAsync(NetworkConfiguration networkConfig)
{ {
var endPoints = new NetworkIPEndPoints(); var endPoints = new NetworkIPEndPointCollection();
bool hasAnyEndPoint = false; bool hasAnyEndPoint = false;
try try

2
CoreAgent.Infrastructure/Services/Network/NetworkIPEndPointManager.cs

@ -24,7 +24,7 @@ public class NetworkIPEndPointManager : INetworkIPEndPointManager
/// 更新 IP 端点信息 /// 更新 IP 端点信息
/// </summary> /// </summary>
/// <param name="endPoints">IP 端点信息集合</param> /// <param name="endPoints">IP 端点信息集合</param>
public void UpdateEndPoints(NetworkIPEndPoints endPoints) public void UpdateEndPoints(NetworkIPEndPointCollection endPoints)
{ {
if (endPoints == null) if (endPoints == null)
{ {

26
CoreAgent.Infrastructure/Services/Network/NetworkInterfaceManager.cs

@ -70,14 +70,14 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
// 验证配置 // 验证配置
if (!ValidateConfig(networkConfig)) if (!ValidateConfig(networkConfig))
{ {
return NetworkInterfaceOperationResult.Failure("网络配置验证失败"); return NetworkInterfaceOperationResult.Failure("网络配置验证失败", NetworkConfigType.None);
} }
var commands = _context.GetNetworkCommandConfig(); var commands = _context.GetNetworkCommandConfig();
var startCommand = commands.NetworkCommands.FirstOrDefault(s => s.Type == NetworkCommandType.NetworkOperation); var startCommand = commands.NetworkCommands.FirstOrDefault(s => s.Type == NetworkCommandType.NetworkOperation);
if (startCommand == null) if (startCommand == null)
{ {
return NetworkInterfaceOperationResult.Failure("未找到启动命令配置"); return NetworkInterfaceOperationResult.Failure("未找到启动命令配置", NetworkConfigType.None);
} }
// 根据配置类型执行不同的启动命令 // 根据配置类型执行不同的启动命令
@ -94,12 +94,12 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
return await ExecuteCoreOnlyStartCommandsAsync(startCommand, networkConfig); return await ExecuteCoreOnlyStartCommandsAsync(startCommand, networkConfig);
} }
return NetworkInterfaceOperationResult.Failure("无有效配置,跳过启动"); return NetworkInterfaceOperationResult.Failure("无有效配置,跳过启动", NetworkConfigType.None);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "启动网络接口失败"); _logger.LogError(ex, "启动网络接口失败");
return NetworkInterfaceOperationResult.Failure($"启动网络接口失败: {ex.Message}"); return NetworkInterfaceOperationResult.Failure($"启动网络接口失败: {ex.Message}", NetworkConfigType.None);
} }
} }
@ -226,8 +226,8 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
_logger.LogInformation("执行RAG配置启动命令: {Command}", fullCommand); _logger.LogInformation("执行RAG配置启动命令: {Command}", fullCommand);
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, new CancellationTokenSource()); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, new CancellationTokenSource());
return result.IsSuccess return result.IsSuccess
? NetworkInterfaceOperationResult.Success() ? NetworkInterfaceOperationResult.Success(NetworkConfigType.RagOnly)
: NetworkInterfaceOperationResult.Failure($"执行RAG配置启动命令失败: {result.Error}"); : NetworkInterfaceOperationResult.Failure($"执行RAG配置启动命令失败: {result.Error}", NetworkConfigType.RagOnly);
} }
private async Task<NetworkInterfaceOperationResult> ExecuteCoreOnlyStartCommandsAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig) private async Task<NetworkInterfaceOperationResult> ExecuteCoreOnlyStartCommandsAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig)
@ -251,9 +251,9 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
var secondaryResults = await Task.WhenAll(secondaryTasks); var secondaryResults = await Task.WhenAll(secondaryTasks);
if (secondaryResults.Any(r => !r.IsSuccess)) if (secondaryResults.Any(r => !r.IsSuccess))
{ {
return NetworkInterfaceOperationResult.Failure("部分次要配置命令执行失败"); return NetworkInterfaceOperationResult.Failure("部分次要配置命令执行失败", NetworkConfigType.CoreOnly);
} }
return NetworkInterfaceOperationResult.Success(); return NetworkInterfaceOperationResult.Success(NetworkConfigType.CoreOnly);
} }
private async Task<NetworkInterfaceOperationResult> ExecuteSingleConfigStartCommandAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig) private async Task<NetworkInterfaceOperationResult> ExecuteSingleConfigStartCommandAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig)
@ -265,8 +265,8 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
_logger.LogInformation("执行单配置启动命令: {Command}", fullCommand); _logger.LogInformation("执行单配置启动命令: {Command}", fullCommand);
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource);
return result.IsSuccess return result.IsSuccess
? NetworkInterfaceOperationResult.Success() ? NetworkInterfaceOperationResult.Success(NetworkConfigType.BothRagAndCore)
: NetworkInterfaceOperationResult.Failure($"执行单配置启动命令失败: {result.Error}"); : NetworkInterfaceOperationResult.Failure($"执行单配置启动命令失败: {result.Error}", NetworkConfigType.BothRagAndCore);
} }
private async Task<NetworkInterfaceOperationResult> ExecuteMultiConfigStartCommandsAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig) private async Task<NetworkInterfaceOperationResult> ExecuteMultiConfigStartCommandsAsync(CommandTemplateConfig startCommand, NetworkConfiguration networkConfig)
@ -289,7 +289,7 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
var secondaryResults = await Task.WhenAll(secondaryTasks); var secondaryResults = await Task.WhenAll(secondaryTasks);
if (secondaryResults.Any(r => !r.IsSuccess)) if (secondaryResults.Any(r => !r.IsSuccess))
{ {
return NetworkInterfaceOperationResult.Failure("部分次要配置命令执行失败"); return NetworkInterfaceOperationResult.Failure("部分次要配置命令执行失败", NetworkConfigType.BothRagAndCore);
} }
// 执行主配置命令 // 执行主配置命令
@ -303,10 +303,10 @@ public class NetworkInterfaceManager : INetworkInterfaceManager
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource);
if (!result.IsSuccess) if (!result.IsSuccess)
{ {
return NetworkInterfaceOperationResult.Failure($"主配置命令执行失败: {result.Error}"); return NetworkInterfaceOperationResult.Failure($"主配置命令执行失败: {result.Error}", NetworkConfigType.BothRagAndCore);
} }
} }
return NetworkInterfaceOperationResult.Success(); return NetworkInterfaceOperationResult.Success(NetworkConfigType.BothRagAndCore);
} }
} }

337
CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs

@ -0,0 +1,337 @@
using CoreAgent.Domain.Helpers;
using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Interfaces.System.Command;
using CoreAgent.Domain.Models.Network;
using CoreAgent.Domain.Models.System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Json;
namespace CoreAgent.Infrastructure.Services.Network;
/// <summary>
/// 网络状态监控管理类
/// </summary>
public class NetworkStatusMonitor : INetworkStatusMonitor
{
private readonly ILogger<NetworkStatusMonitor> _logger;
private readonly ISystemCommandExecutor _commandExecutor;
private readonly AppSettings _appSettings;
public NetworkStatusMonitor(
ILogger<NetworkStatusMonitor> logger,
ISystemCommandExecutor commandExecutor,
IOptions<AppSettings> appSettings)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor));
_appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings));
}
/// <summary>
/// 检查所有网络端点的状态
/// </summary>
/// <param name="endPoints">网络端点信息</param>
/// <param name="configType">网络配置类型</param>
/// <param name="timeoutSeconds">超时时间(秒),默认30秒</param>
/// <returns>检查结果</returns>
public async Task<NetworkStatusCheckResult> CheckAllEndPointsStatusAsync(
NetworkIPEndPointCollection endPoints,
NetworkConfigType configType,
int? timeoutSeconds = null)
{
var result = new NetworkStatusCheckResult();
var startTime = DateTime.Now;
var timeout = TimeSpan.FromSeconds(timeoutSeconds ?? _appSettings.NetworkStatusCheckTimeout);
try
{
_logger.LogInformation("开始检查网络端点状态,配置类型: {ConfigType}, 超时时间: {TimeoutSeconds}秒",
configType, timeout.TotalSeconds);
// 先执行一次检查
var checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
result.IsSuccess = checkResults.All(r => r.IsSuccess);
// 如果检查失败,进入重试循环
while (!result.IsSuccess && DateTime.Now - startTime < timeout)
{
var failedEndpoints = checkResults.Where(r => !r.IsSuccess)
.Select(r => $"{r.ComAddr}: {r.ErrorMessage}");
var errorMessage = string.Join("; ", failedEndpoints);
_logger.LogWarning("网络端点状态检查未通过,失败端点: {FailedEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒",
errorMessage, (DateTime.Now - startTime).TotalSeconds);
await Task.Delay(1000); // 等待1秒后重试
// 重试检查
checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
result.IsSuccess = checkResults.All(r => r.IsSuccess);
}
if (!result.IsSuccess)
{
result.ErrorMessage = new string[] { $"检查超时,已超过{timeout.TotalSeconds}秒" };
_logger.LogWarning("网络端点状态检查超时,配置类型: {ConfigType}", configType);
}
else
{
_logger.LogInformation("网络端点状态检查成功,配置类型: {ConfigType}, 耗时: {ElapsedTime}秒",
configType, (DateTime.Now - startTime).TotalSeconds);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "检查网络端点状态时发生错误,配置类型: {ConfigType}", configType);
result.IsSuccess = false;
result.ErrorMessage = new string[] { $"检查过程发生异常: {ex.Message}" };
}
return result;
}
/// <summary>
/// 根据配置类型检查相应的端点状态
/// </summary>
/// <returns>所有端点的检查结果</returns>
private async Task<EndPointStatusResult[]> CheckEndPointsByConfigTypeAsync(NetworkIPEndPointCollection endPoints, NetworkConfigType configType)
{
var results = new List<EndPointStatusResult>();
switch (configType)
{
case NetworkConfigType.BothRagAndCore:
var ragResult = await CheckRagEndPointsAsync(endPoints);
results.Add(ragResult);
var coreResult = await CheckCoreEndPointsAsync(endPoints);
results.Add(coreResult);
break;
case NetworkConfigType.RagOnly:
var ragOnlyResult = await CheckRagEndPointsAsync(endPoints);
results.Add(ragOnlyResult);
break;
case NetworkConfigType.CoreOnly:
var coreOnlyResult = await CheckCoreEndPointsAsync(endPoints);
results.Add(coreOnlyResult);
break;
case NetworkConfigType.None:
default:
_logger.LogWarning("无需检查网络端点状态,配置类型: {ConfigType}", configType);
break;
}
return results.ToArray();
}
/// <summary>
/// 检查 RAG 相关端点状态
/// </summary>
/// <returns>检查结果</returns>
private async Task<EndPointStatusResult> CheckRagEndPointsAsync(NetworkIPEndPointCollection endPoints)
{
var result = new EndPointStatusResult();
if (endPoints.RanEndPoint == null)
{
result.IsSuccess = true;
return result;
}
result.ComAddr = endPoints.RanEndPoint.ComAddr;
var ranResult = await CheckRanStatusAsync(endPoints.RanEndPoint);
_logger.LogInformation("RAN 端点状态检查: {ComAddr}, 结果: {IsSuccess}",
ranResult.ComAddr, ranResult.IsSuccess);
result.IsSuccess = ranResult.IsSuccess;
result.ErrorMessage = ranResult.ErrorMessage;
return result;
}
/// <summary>
/// 检查 Core 相关端点状态
/// </summary>
/// <returns>检查结果</returns>
private async Task<EndPointStatusResult> CheckCoreEndPointsAsync(NetworkIPEndPointCollection endPoints)
{
var result = new EndPointStatusResult { IsSuccess = true };
var errorMessages = new List<string>();
// 检查 IMS 端点
if (endPoints.ImsEndPoints != null && endPoints.ImsEndPoints.Any())
{
var imsResults = await CheckImsStatusAsync(endPoints.ImsEndPoints);
foreach (var imsResult in imsResults)
{
_logger.LogInformation("IMS 端点状态检查: {ComAddr}, 结果: {IsSuccess}",
imsResult.ComAddr, imsResult.IsSuccess);
if (!imsResult.IsSuccess)
{
result.IsSuccess = false;
errorMessages.Add($"IMS端点 {imsResult.ComAddr}: {imsResult.ErrorMessage}");
}
}
}
// 检查 CN 端点
if (endPoints.CnEndPoints != null && endPoints.CnEndPoints.Any())
{
var cnResults = await CheckCnStatusAsync(endPoints.CnEndPoints);
foreach (var cnResult in cnResults)
{
_logger.LogInformation("CN 端点状态检查: {ComAddr}, 结果: {IsSuccess}",
cnResult.ComAddr, cnResult.IsSuccess);
if (!cnResult.IsSuccess)
{
result.IsSuccess = false;
errorMessages.Add($"CN端点 {cnResult.ComAddr}: {cnResult.ErrorMessage}");
}
}
}
if (!result.IsSuccess)
{
result.ErrorMessage = string.Join("; ", errorMessages);
}
return result;
}
/// <summary>
/// 检查 RAN 端点状态
/// </summary>
/// <param name="ranEndPoint">RAN 端点信息</param>
/// <returns>RAN 端点状态</returns>
public async Task<EndPointStatusResult> CheckRanStatusAsync(RanIPEndPoint ranEndPoint)
{
var result = new EndPointStatusResult();
if (ranEndPoint == null)
{
result.IsSuccess = false;
result.ErrorMessage = "RAN 端点未配置";
_logger.LogWarning(result.ErrorMessage);
return result;
}
result.ComAddr = ranEndPoint.ComAddr;
try
{
await CheckEndPointStatusAsync(ranEndPoint.ComAddr, "RAN");
result.IsSuccess = true;
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
_logger.LogError(ex, "检查 RAN 端点状态失败");
}
return result;
}
/// <summary>
/// 检查 IMS 端点状态
/// </summary>
/// <param name="imsEndPoints">IMS 端点信息列表</param>
/// <returns>IMS 端点状态列表</returns>
public async Task<List<EndPointStatusResult>> CheckImsStatusAsync(List<ImsIPEndPoint> imsEndPoints)
{
var result = new List<EndPointStatusResult>();
if (imsEndPoints == null || !imsEndPoints.Any())
{
return result;
}
foreach (var imsEndPoint in imsEndPoints)
{
var statusResult = new EndPointStatusResult
{
ComAddr = imsEndPoint.ComAddr
};
try
{
await CheckEndPointStatusAsync(imsEndPoint.ComAddr, "IMS");
statusResult.IsSuccess = true;
}
catch (Exception ex)
{
statusResult.IsSuccess = false;
statusResult.ErrorMessage = ex.Message;
_logger.LogError(ex, "检查 IMS 端点 {ComAddr} 状态失败", imsEndPoint.ComAddr);
}
result.Add(statusResult);
}
return result;
}
/// <summary>
/// 检查 CN 端点状态
/// </summary>
/// <param name="cnEndPoints">CN 端点信息列表</param>
/// <returns>CN 端点状态列表</returns>
public async Task<List<EndPointStatusResult>> CheckCnStatusAsync(List<CnIPEndPoint> cnEndPoints)
{
var result = new List<EndPointStatusResult>();
if (cnEndPoints == null || !cnEndPoints.Any())
{
return result;
}
foreach (var cnEndPoint in cnEndPoints)
{
var statusResult = new EndPointStatusResult
{
ComAddr = cnEndPoint.ComAddr
};
try
{
await CheckEndPointStatusAsync(cnEndPoint.ComAddr, "CN");
statusResult.IsSuccess = true;
}
catch (Exception ex)
{
statusResult.IsSuccess = false;
statusResult.ErrorMessage = ex.Message;
_logger.LogError(ex, "检查 CN 端点 {ComAddr} 状态失败", cnEndPoint.ComAddr);
}
result.Add(statusResult);
}
return result;
}
/// <summary>
/// 检查单个端点的状态
/// </summary>
/// <param name="comAddr">通信地址</param>
/// <param name="endPointType">端点类型</param>
private async Task<(bool isSuccess, string data)> CheckEndPointStatusAsync(string comAddr, string endPointType)
{
var command = $"{_appSettings.WebSocketJsPath} {comAddr} '{_appSettings.WebSocketCommands.Stats.ToJson()}'";
var result = await _commandExecutor.ExecuteCommandAsync(command, new CancellationTokenSource());
if (result.IsSuccess)
{
_logger.LogInformation("{EndPointType} 端点 {ComAddr} 状态检查成功", endPointType, comAddr);
return (result.IsSuccess, result.Output.ParseWsResultLogs());
}
else
{
var error = $"检查失败: {result.Error}";
_logger.LogWarning("{EndPointType} 端点 {ComAddr} 状态检查失败: {Error}", endPointType, comAddr, result.Error);
return (result.IsSuccess, result.Output.ParseWsResultLogs());
}
}
}
Loading…
Cancel
Save