feat: add headless agent management to CLI and both desktop clients
This commit is contained in:
1 parent
e91fa0235c
commit
6916dd54fb
50 files changed
+4837
-148
No files matched your search
@@ -0,0 +1,203 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
namespace Ads.Desktop;
|
||||
|
||||
public partial class AgentManagementViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
[ObservableProperty] private bool localMode;
|
||||
[ObservableProperty] private string adminToken = "";
|
||||
[ObservableProperty] private string enrollmentToken = "";
|
||||
[ObservableProperty] private string configPath = DefaultConfig();
|
||||
[ObservableProperty] private ManagedAgent? selectedAgent;
|
||||
[ObservableProperty] private ManagedDevice? selectedManagedDevice;
|
||||
[ObservableProperty] private string deviceId = "";
|
||||
[ObservableProperty] private string target = "";
|
||||
[ObservableProperty] private string adbSerial = "";
|
||||
[ObservableProperty] private string adbServer = "";
|
||||
[ObservableProperty] private string configJson = "";
|
||||
[ObservableProperty] private string remoteLogText = "";
|
||||
[ObservableProperty] private string notice = "管理员凭据用于远程管理;也可切换为管理本机 Agent。";
|
||||
[ObservableProperty] private bool isBusy;
|
||||
[ObservableProperty] private bool autoRefresh = true;
|
||||
[ObservableProperty] private bool followLogs;
|
||||
public ObservableCollection<ManagedAgent> Agents { get; } = new();
|
||||
public ObservableCollection<ManagedDevice> AgentDevices { get; } = new();
|
||||
private readonly Func<(string Server,string Origin)> server;
|
||||
private readonly Action<string> log;
|
||||
private readonly CancellationTokenSource lifetime = new();
|
||||
private readonly DispatcherTimer timer;
|
||||
private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
|
||||
private bool polling, disposed;
|
||||
private long logCursor;
|
||||
private string logInstance = "";
|
||||
private string listedSource = "";
|
||||
private string SourceKey()=>LocalMode ? "local:"+ConfigPath : "remote:"+JsonSerializer.Serialize(new[]{server().Server,server().Origin});
|
||||
private string? lastError;
|
||||
public AgentManagementViewModel(Func<(string,string)> server, Action<string>? logger=null, bool background=true, bool credentials=true)
|
||||
{
|
||||
this.server=server; log=logger ?? (_=>{});
|
||||
var (initialServer,initialOrigin)=server();
|
||||
ConfigJson=JsonSerializer.Serialize(new {version=1,id="local-pc",name=Environment.MachineName,server=initialServer,connect_address=string.IsNullOrWhiteSpace(initialOrigin)?null:initialOrigin,adb_server="127.0.0.1:5037",devices=Array.Empty<object>()}, new JsonSerializerOptions{WriteIndented=true});
|
||||
if(credentials) {
|
||||
var path=DesktopPaths.ProjectRoot() is {} root ? Path.Combine(root,"config","private","admin.env") : Path.Combine(AppContext.BaseDirectory,"admin.env");
|
||||
if(File.Exists(path)) { try { ImportAdmin(path); } catch { } }
|
||||
}
|
||||
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(5)};
|
||||
timer.Tick+=async(_,_)=>await PollAsync(); if(background)timer.Start();
|
||||
}
|
||||
public static string DefaultConfig() => OperatingSystem.IsWindows()
|
||||
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AndroidDeviceStreaming","agent","agent.json")
|
||||
: Path.Combine(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".config"),"ads","agent.json");
|
||||
public void StartMonitoring()=>timer.Start();
|
||||
private string Redact(string value) { foreach(var secret in secrets) value=value.Replace(secret,"[REDACTED]",StringComparison.Ordinal);return value; }
|
||||
partial void OnAdminTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
|
||||
partial void OnEnrollmentTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
|
||||
partial void OnSelectedAgentChanged(ManagedAgent? value)
|
||||
{
|
||||
var selected=SelectedManagedDevice?.Id; AgentDevices.Clear();
|
||||
foreach(var device in value?.Status.Devices ?? [])AgentDevices.Add(device);
|
||||
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selected) ?? AgentDevices.FirstOrDefault();
|
||||
logCursor=0;logInstance="";RemoteLogText="";UpdateCommands();
|
||||
}
|
||||
partial void OnSelectedManagedDeviceChanged(ManagedDevice? value)=>UpdateCommands();
|
||||
partial void OnIsBusyChanged(bool value)=>UpdateCommands();
|
||||
partial void OnLocalModeChanged(bool value){Agents.Clear();SelectedAgent=null;Notice=value?"管理本机 Agent,不需要管理员令牌。":"管理控制中心中的 Agent,需要独立管理员凭据。";}
|
||||
private bool CanManage()=>!IsBusy && SelectedAgent?.Online==true;
|
||||
private bool CanDevice()=>CanManage() && SelectedManagedDevice!=null;
|
||||
private bool CanRestart()=>CanManage() && SelectedAgent?.Status.Supervised==true;
|
||||
private bool CanLocal()=>!IsBusy && LocalMode;
|
||||
private void UpdateCommands()
|
||||
{
|
||||
LoadConfigCommand.NotifyCanExecuteChanged();SaveConfigCommand.NotifyCanExecuteChanged();AddDeviceCommand.NotifyCanExecuteChanged();
|
||||
RemoveDeviceCommand.NotifyCanExecuteChanged();EnableDeviceCommand.NotifyCanExecuteChanged();DisableDeviceCommand.NotifyCanExecuteChanged();
|
||||
ReadLogsCommand.NotifyCanExecuteChanged();RestartAgentCommand.NotifyCanExecuteChanged();
|
||||
InitializeLocalCommand.NotifyCanExecuteChanged();StartLocalCommand.NotifyCanExecuteChanged();InstallServiceCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
public void ImportAdmin(string path)
|
||||
{
|
||||
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
|
||||
var token=File.ReadLines(path).Select(l=>l.Split('=',2)).FirstOrDefault(p=>p.Length==2&&p[0].Trim()=="ADS_ADMIN_TOKEN")?.ElementAt(1).Trim();
|
||||
if(string.IsNullOrEmpty(token)||token.Length<32||token.Contains('\r')||token.Contains('\n'))throw new InvalidOperationException("文件中没有有效的 ADS_ADMIN_TOKEN。");
|
||||
AdminToken=token;Notice="管理员凭据已加载,内容仅保存在内存中。";
|
||||
}
|
||||
public void ImportEnrollment(string path)
|
||||
{
|
||||
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
|
||||
var value=File.ReadLines(path).FirstOrDefault(l=>l.StartsWith("ADS_AGENT_TOKEN=",StringComparison.Ordinal))?[16..].Trim();
|
||||
if(string.IsNullOrEmpty(value)||value.Length<32)throw new InvalidOperationException("文件中没有有效的 ADS_AGENT_TOKEN。");
|
||||
EnrollmentToken=value;Notice="设备端凭据已加载,仅供本机初始化使用。";
|
||||
}
|
||||
private RelayOptions Options(){var(s,o)=server();return RelayOptions.Parse(s,o,AdminToken);}
|
||||
private async Task Guard(Func<Task> action)
|
||||
{
|
||||
if(IsBusy)return;IsBusy=true;
|
||||
try { await action(); }
|
||||
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
|
||||
catch(Exception error){Notice=Redact(error.Message);log("[Agent管理] "+Notice);}
|
||||
finally{IsBusy=false;}
|
||||
}
|
||||
private async Task<JsonElement> LocalRequestAsync(object request)
|
||||
{
|
||||
var executable=DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl");
|
||||
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;
|
||||
using var process=Process.Start(info) ?? throw new InvalidOperationException("adsctl 无法启动。");
|
||||
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
|
||||
await process.StandardInput.WriteAsync(JsonSerializer.Serialize(request));process.StandardInput.Close();
|
||||
try { await process.WaitForExitAsync(lifetime.Token).WaitAsync(TimeSpan.FromSeconds(20),lifetime.Token); }
|
||||
catch { if(!process.HasExited)process.Kill(entireProcessTree:true);throw; }
|
||||
if(process.ExitCode!=0)throw new InvalidOperationException((await error).Trim());
|
||||
using var value=JsonDocument.Parse(await output);return value.RootElement.Clone();
|
||||
}
|
||||
private Task<JsonElement> CallAsync(object request,string? agent=null) {
|
||||
if(listedSource!=SourceKey())throw new InvalidOperationException("管理地址或配置路径已改变,请先刷新 Agent 列表。");
|
||||
return LocalMode ? LocalRequestAsync(request) : AgentManagementApi.CallAsync(Options(),agent ?? SelectedAgent?.Id ?? throw new InvalidOperationException("请选择 Agent。"),request,lifetime.Token);
|
||||
}
|
||||
private async Task RefreshCoreAsync()
|
||||
{
|
||||
var selected=SelectedAgent?.Id;var selectedDevice=SelectedManagedDevice?.Id;
|
||||
var local=LocalMode;var path=ConfigPath;var source=server();
|
||||
ManagedAgent[] rows;
|
||||
if(LocalMode) {
|
||||
var value=await LocalRequestAsync(new{op="status"});
|
||||
var status=value.Deserialize<ManagedStatus>(new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? throw new InvalidOperationException("Agent 状态无效。");
|
||||
rows=[new ManagedAgent(status.Id,true,DateTimeOffset.UtcNow.ToUnixTimeSeconds(),status)];
|
||||
}else rows=await AgentManagementApi.ListAsync(Options(),lifetime.Token);
|
||||
if(local!=LocalMode||path!=ConfigPath||source!=server())return;
|
||||
listedSource=SourceKey();
|
||||
Agents.Clear();foreach(var row in rows)Agents.Add(row);
|
||||
var chosen=Agents.FirstOrDefault(r=>r.Id==selected) ?? Agents.FirstOrDefault(r=>r.Online) ?? Agents.FirstOrDefault();
|
||||
// Preserve log cursor and draft configuration during periodic metadata refreshes.
|
||||
var cursor=logCursor;var instance=logInstance;var text=RemoteLogText;
|
||||
SelectedAgent=chosen;
|
||||
if(selected==chosen?.Id){logCursor=cursor;logInstance=instance;RemoteLogText=text;}
|
||||
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selectedDevice) ?? AgentDevices.FirstOrDefault();
|
||||
Notice=$"{rows.Length} 个 Agent · {rows.Count(r=>r.Online)} 个在线";lastError=null;
|
||||
}
|
||||
[RelayCommand]private Task RefreshAgentsAsync()=>Guard(RefreshCoreAsync);
|
||||
[RelayCommand(CanExecute=nameof(CanManage))]private Task LoadConfigAsync()=>Guard(async()=>{
|
||||
var value=await CallAsync(new{op="config_get"});ConfigJson=JsonSerializer.Serialize(value,new JsonSerializerOptions{WriteIndented=true});Notice="已读取配置,凭据不在配置中。";
|
||||
});
|
||||
[RelayCommand(CanExecute=nameof(CanManage))]private Task SaveConfigAsync()=>Guard(async()=>{
|
||||
using var doc=JsonDocument.Parse(ConfigJson);await CallAsync(new{op="config_set",config=doc.RootElement});await RefreshCoreAsync();Notice="配置已持久化并应用。受影响设备将重建连接。";
|
||||
});
|
||||
[RelayCommand(CanExecute=nameof(CanManage))]private Task AddDeviceAsync()=>Guard(async()=>{
|
||||
if(string.IsNullOrWhiteSpace(Target)==string.IsNullOrWhiteSpace(AdbSerial))throw new InvalidOperationException("手机地址与 ADB 序列号必须填写其中一项。");
|
||||
await CallAsync(new{op="device_add",device=new{id=DeviceId.Trim(),target=string.IsNullOrWhiteSpace(Target)?null:Target.Trim(),adb_serial=string.IsNullOrWhiteSpace(AdbSerial)?null:AdbSerial.Trim(),adb_server=string.IsNullOrWhiteSpace(AdbServer)?null:AdbServer.Trim(),device_port=5555,enabled=true}});
|
||||
await RefreshCoreAsync();Notice="手机已添加并启动连接。";
|
||||
});
|
||||
private Task DeviceOperation(string operation,bool? enabled=null)=>Guard(async()=>{
|
||||
var id=SelectedManagedDevice?.Id ?? throw new InvalidOperationException("请选择手机。");
|
||||
await CallAsync(enabled.HasValue?new{op=operation,id,enabled=enabled.Value}:(object)new{op=operation,id});await RefreshCoreAsync();
|
||||
});
|
||||
[RelayCommand(CanExecute=nameof(CanDevice))]private Task RemoveDeviceAsync()=>DeviceOperation("device_remove");
|
||||
[RelayCommand(CanExecute=nameof(CanDevice))]private Task EnableDeviceAsync()=>DeviceOperation("device_enable",true);
|
||||
[RelayCommand(CanExecute=nameof(CanDevice))]private Task DisableDeviceAsync()=>DeviceOperation("device_enable",false);
|
||||
private async Task LogsCoreAsync()
|
||||
{
|
||||
var page=await CallAsync(new{op="logs",after=logCursor,limit=50});var instance=page.GetProperty("instance").GetString() ?? "";
|
||||
if(logInstance.Length>0&&instance!=logInstance){logCursor=0;RemoteLogText="";logInstance=instance;return;}
|
||||
logInstance=instance;logCursor=page.GetProperty("next").GetInt64();
|
||||
foreach(var entry in page.GetProperty("entries").EnumerateArray())RemoteLogText+=Redact($"{entry.GetProperty("time")} {entry.GetProperty("level")} {entry.GetProperty("message").GetString()}\n");
|
||||
if(RemoteLogText.Length>100000)RemoteLogText=RemoteLogText[^100000..];
|
||||
}
|
||||
[RelayCommand(CanExecute=nameof(CanManage))]private Task ReadLogsAsync()=>Guard(LogsCoreAsync);
|
||||
[RelayCommand(CanExecute=nameof(CanRestart))]private Task RestartAgentAsync()=>Guard(async()=>{await CallAsync(new{op="restart"});Notice="监督进程将重启 Agent,手机连接会短暂中断。";});
|
||||
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InitializeLocalAsync()=>Guard(async()=>{
|
||||
if(File.Exists(ConfigPath))throw new InvalidOperationException("本机配置已存在,请读取后修改。");
|
||||
using var doc=JsonDocument.Parse(ConfigJson);var root=doc.RootElement;
|
||||
var args=new List<string>{"--json","--config",ConfigPath,"--server",root.GetProperty("server").GetString()!,"init","--id",root.GetProperty("id").GetString()!,"--name",root.GetProperty("name").GetString()!};
|
||||
// Origin is a global CLI option and must precede the subcommand.
|
||||
if(root.TryGetProperty("connect_address",out var origin)&&origin.ValueKind==JsonValueKind.String)args.InsertRange(5,["--connect-address",origin.GetString()!]);
|
||||
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl"),args);info.Environment["ADS_AGENT_TOKEN"]=EnrollmentToken;
|
||||
var result=await ProcessTools.RunAsync(info,lifetime.Token);if(result.ExitCode!=0)throw new InvalidOperationException(result.Error);
|
||||
EnrollmentToken="";Notice="本机配置已初始化,可启动后台 Agent 后应用设备配置。";
|
||||
});
|
||||
[RelayCommand(CanExecute=nameof(CanLocal))]private Task StartLocalAsync()=>Guard(async()=>{
|
||||
try { await LocalRequestAsync(new{op="status"});Notice="本机 Agent 已在运行。";return; } catch(InvalidOperationException){}
|
||||
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-agent"),"ads-agent"),["--quiet","--supervise","--config",ConfigPath]);
|
||||
info.RedirectStandardOutput=false;info.RedirectStandardError=false;
|
||||
using var process=Process.Start(info) ?? throw new InvalidOperationException("Agent 启动失败。");
|
||||
await Task.Delay(700,lifetime.Token);await RefreshCoreAsync();Notice="后台 Agent 已启动,退出托盘不会停止它。";
|
||||
});
|
||||
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InstallServiceAsync()=>Guard(async()=>{
|
||||
if(!OperatingSystem.IsWindows())throw new InvalidOperationException("请在终端运行 adsctl service install;系统级服务可加 --system。");
|
||||
var info=new ProcessStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl")){UseShellExecute=true,Verb="runas",WindowStyle=ProcessWindowStyle.Hidden};
|
||||
foreach(var value in new[]{"--config",ConfigPath,"service","install"})info.ArgumentList.Add(value);
|
||||
using var process=Process.Start(info) ?? throw new InvalidOperationException("安装命令无法启动。");await process.WaitForExitAsync(lifetime.Token);
|
||||
if(process.ExitCode!=0)throw new InvalidOperationException("服务安装失败,请在管理员终端使用 adsctl 检查错误。");
|
||||
await RefreshCoreAsync();Notice="已配置无界面开机启动。";
|
||||
});
|
||||
private async Task PollAsync()
|
||||
{
|
||||
if(polling||disposed||IsBusy||!AutoRefresh||(!LocalMode&&AdminToken.Length<32))return;polling=true;IsBusy=true;
|
||||
try { await RefreshCoreAsync();if(FollowLogs&&SelectedAgent?.Online==true)await LogsCoreAsync(); }
|
||||
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
|
||||
catch(Exception error){var message=Redact(error.Message);Notice=message;if(message!=lastError){log("[Agent管理] "+message);lastError=message;}}
|
||||
finally{polling=false;IsBusy=false;}
|
||||
}
|
||||
public void Dispose(){if(disposed)return;disposed=true;timer.Stop();lifetime.Cancel();lifetime.Dispose();}
|
||||
}
|
||||
Reference in new issue
Block a user