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,181 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'manager_repository.dart';
|
||||
|
||||
typedef JsonMap = Map<String, Object?>;
|
||||
|
||||
abstract interface class AgentApi {
|
||||
String get connectionKey;
|
||||
Future<List<JsonMap>> list();
|
||||
Future<Object?> request(String agent, JsonMap operation);
|
||||
Future<Object?> local(String config, JsonMap operation);
|
||||
Future<void> importAdmin(String path);
|
||||
Future<void> initialize(String path, JsonMap config, String token);
|
||||
Future<void> start(String path);
|
||||
Future<void> install(String path);
|
||||
String redact(String message);
|
||||
}
|
||||
|
||||
class AgentService implements AgentApi {
|
||||
AgentService(this.manager);
|
||||
final ManagerRepository manager;
|
||||
@override
|
||||
String get connectionKey =>
|
||||
jsonEncode([manager.settings.server, manager.settings.origin]);
|
||||
String _token = '';
|
||||
final Set<String> _secrets = {};
|
||||
@override
|
||||
String redact(String message) {
|
||||
for (final secret in _secrets) {
|
||||
message = message.replaceAll(secret, '[REDACTED]');
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> importAdmin(String path) async {
|
||||
final file = File(path);
|
||||
if (await file.length() > 65536) {
|
||||
throw const FormatException('凭据文件过大');
|
||||
}
|
||||
final line = (await file.readAsLines())
|
||||
.where((v) => v.startsWith('ADS_ADMIN_TOKEN='))
|
||||
.firstOrNull;
|
||||
final token = line?.substring(16).trim() ?? '';
|
||||
if (token.length < 32 || token.contains(RegExp(r'[\r\n]'))) {
|
||||
throw const FormatException('请选择包含 ADS_ADMIN_TOKEN 的 admin.env');
|
||||
}
|
||||
_token = token;
|
||||
_secrets.add(token);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<JsonMap>> list() async {
|
||||
final value =
|
||||
await manager.requestJson('v3/agents', bearer: _token) as List<Object?>;
|
||||
return value.map((v) => Map<String, Object?>.from(v! as Map)).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Object?> request(String agent, JsonMap operation) async {
|
||||
final value = await manager.requestJson(
|
||||
'v3/rpc',
|
||||
bearer: _token,
|
||||
payload: operation,
|
||||
query: {'agent': agent},
|
||||
) as Map<String, dynamic>;
|
||||
if (value['ok'] != true) {
|
||||
throw StateError(redact(value['error'] as String? ?? 'Agent 管理请求失败'));
|
||||
}
|
||||
return value['data'];
|
||||
}
|
||||
|
||||
Future<ProcessResult> _cli(
|
||||
List<String> args, {
|
||||
String? input,
|
||||
Map<String, String>? extra,
|
||||
}) async {
|
||||
final child = await Process.start(
|
||||
manager.findTool('adsctl'),
|
||||
args,
|
||||
environment: {...manager.environment(), ...?extra},
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
final out = child.stdout.transform(utf8.decoder).join();
|
||||
final error = child.stderr.transform(utf8.decoder).join();
|
||||
if (input != null) {
|
||||
child.stdin.write(input);
|
||||
}
|
||||
await child.stdin.close();
|
||||
try {
|
||||
final code = await child.exitCode.timeout(const Duration(seconds: 22));
|
||||
final result = ProcessResult(child.pid, code, await out, await error);
|
||||
if (code != 0) {
|
||||
throw StateError(redact(result.stderr as String));
|
||||
}
|
||||
return result;
|
||||
} on TimeoutException {
|
||||
child.kill();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Object?> local(String config, JsonMap operation) async {
|
||||
final result = await _cli([
|
||||
'--json',
|
||||
'--config',
|
||||
config,
|
||||
'request',
|
||||
], input: jsonEncode(operation));
|
||||
return jsonDecode(result.stdout as String);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> initialize(String path, JsonMap config, String token) async {
|
||||
if (token.length < 32) {
|
||||
throw const FormatException('请导入有效设备端凭据');
|
||||
}
|
||||
_secrets.add(token);
|
||||
final args = [
|
||||
'--json',
|
||||
'--config',
|
||||
path,
|
||||
'--server',
|
||||
config['server']! as String,
|
||||
if (config['connect_address'] case final String origin) ...[
|
||||
'--connect-address',
|
||||
origin,
|
||||
],
|
||||
'init',
|
||||
'--id',
|
||||
config['id']! as String,
|
||||
'--name',
|
||||
config['name']! as String,
|
||||
];
|
||||
await _cli(args, extra: {'ADS_AGENT_TOKEN': token});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> start(String path) async {
|
||||
try {
|
||||
await local(path, {'op': 'status'});
|
||||
return;
|
||||
} on StateError {
|
||||
/* The private IPC lock prevents a duplicate daemon. */
|
||||
}
|
||||
await Process.start(
|
||||
manager.findTool('ads-agent'),
|
||||
['--quiet', '--supervise', '--config', path],
|
||||
mode: ProcessStartMode.detached,
|
||||
environment: manager.environment(),
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 700));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> install(String path) async {
|
||||
if (!Platform.isWindows) {
|
||||
throw UnsupportedError('请在终端运行 adsctl service install,系统级服务加 --system');
|
||||
}
|
||||
String quote(String text) => "'${text.replaceAll("'", "''")}'";
|
||||
final exe = manager.findTool('adsctl');
|
||||
final escaped = '"${p.absolute(path)}"';
|
||||
final script =
|
||||
'\$p=Start-Process -FilePath ${quote(exe)} -ArgumentList @(\'--config\',${quote(escaped)},\'service\',\'install\') -Verb RunAs -WindowStyle Hidden -PassThru -Wait;exit \$p.ExitCode';
|
||||
final result = await Process.run(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-Command', script],
|
||||
environment: manager.environment(),
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('开机服务安装失败,请在管理员终端检查 adsctl service install');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user