You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
2.2 KiB
57 lines
2.2 KiB
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;
|
|
|
|
/// <summary>
|
|
/// 命令执行器基类
|
|
/// </summary>
|
|
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<string> outputHandler, CancellationTokenSource cancellationTokenSource);
|
|
|
|
public abstract Task<CommandExecutionResult> ExecuteCommandAsync(string command, CancellationTokenSource cancellationTokenSource);
|
|
|
|
protected async Task<CommandExecutionResult> 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);
|
|
}
|
|
}
|
|
}
|