using CliWrap; using CliWrap.Buffered; using CoreAgent.Domain.Interfaces.System.Command; using CoreAgent.Domain.Models; using CoreAgent.Domain.Models.System; using Microsoft.Extensions.Logging; namespace CoreAgent.Infrastructure.Command.Base; /// /// 命令执行器基类 /// public abstract class BaseCommandExecutor : ISystemCommandExecutor { protected readonly ILogger _logger; protected abstract string DefaultShell { get; } protected BaseCommandExecutor(ILogger logger) { _logger = logger; } public abstract Task ExecuteCommandWithOutputAsync(string command, Action outputHandler, CancellationTokenSource cancellationTokenSource); public abstract Task ExecuteCommandAsync(string command, CancellationTokenSource cancellationTokenSource); protected async Task ExecuteCommandInternalAsync(string command, string arguments, CancellationTokenSource cancellationTokenSource) { var startTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); try { _logger.LogDebug("开始执行命令: {Command}", command); var cmd = Cli.Wrap(DefaultShell) .WithArguments(arguments) .WithValidation(CommandResultValidation.None); var result = await cmd.ExecuteBufferedAsync(cancellationTokenSource.Token); var executionTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - startTime; if (result.IsSuccess) { _logger.LogDebug("命令执行成功 - 输出: {Output}", result.StandardOutput); return CommandExecutionResult.Success(result.StandardOutput, executionTime); } else { _logger.LogDebug("命令执行失败 - 错误: {Error}", result.StandardError); return CommandExecutionResult.Failure(result.StandardError, executionTime); } } catch (Exception ex) { var executionTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - startTime; _logger.LogError(ex, "命令执行失败: {Command}", command); return CommandExecutionResult.Failure(ex.Message, executionTime); } } }