Monitor ADB device presence and withdraw stale registrations in 0.2.6
This commit is contained in:
1 parent
03e729a60b
commit
dc29a20a41
17 files changed
+488
-23
No files matched your search
Generated
+6
-6
@@ -4,7 +4,7 @@ version = 4
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ads-agent"
|
name = "ads-agent"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ads-core",
|
"ads-core",
|
||||||
"ads-management",
|
"ads-management",
|
||||||
@@ -21,7 +21,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ads-client"
|
name = "ads-client"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ads-core",
|
"ads-core",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
@@ -32,7 +32,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ads-core"
|
name = "ads-core"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -51,7 +51,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ads-management"
|
name = "ads-management"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ads-core",
|
"ads-core",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
@@ -67,7 +67,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ads-usb"
|
name = "ads-usb"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -78,7 +78,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "adsctl"
|
name = "adsctl"
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ads-core",
|
"ads-core",
|
||||||
"ads-management",
|
"ads-management",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ members = ["crates/ads-core", "agent", "client", "usb", "crates/ads-management",
|
|||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.5"
|
version = "0.2.6"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
|
|||||||
@@ -250,3 +250,5 @@ Windows 发布精简:Avalonia 合并托管程序集、保留原生库;Flutte
|
|||||||
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
|
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
|
||||||
|
|
||||||
Linux 桌面 deb 安装后自动通过 update-alternatives 注册 `/usr/bin/adsctl`、`ads-agent`、`ads-client`、`ads-usb`,支持多包共存及卸载回退;无需手动创建链接,详见 [Linux 打包](docs/linux-packaging.md)。
|
Linux 桌面 deb 安装后自动通过 update-alternatives 注册 `/usr/bin/adsctl`、`ads-agent`、`ads-client`、`ads-usb`,支持多包共存及卸载回退;无需手动创建链接,详见 [Linux 打包](docs/linux-packaging.md)。
|
||||||
|
|
||||||
|
已配置的 Agent ADB 设备会持续检测上下线,离线撤销注册、恢复沿用原 ID;同一 ADB server 共享查询,未配置的新手机仍需手动添加。详见 [Agent 管理与设备监听](docs/agent-management.md#持续监听设备上下线026)。
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
//! One bounded ADB snapshot query per server, shared by all configured phones.
|
||||||
|
use std::{collections::BTreeMap, time::Duration};
|
||||||
|
use tokio::{sync::watch, task::JoinHandle};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Snapshot {
|
||||||
|
Pending,
|
||||||
|
Unavailable(String),
|
||||||
|
Devices(BTreeMap<String, String>),
|
||||||
|
}
|
||||||
|
impl Snapshot {
|
||||||
|
pub fn error_for(&self, serial: &str) -> Option<String> {
|
||||||
|
match self {
|
||||||
|
Self::Pending => Some("正在确认 ADB 设备状态".into()),
|
||||||
|
Self::Unavailable(error) => Some(format!("ADB 服务不可达:{error}")),
|
||||||
|
Self::Devices(devices) => match devices.get(serial).map(String::as_str) {
|
||||||
|
Some("device") => None,
|
||||||
|
Some("unauthorized") => Some("ADB 设备未授权,请在手机上允许 USB 调试".into()),
|
||||||
|
Some(state) => Some(format!("ADB 设备不可用:{state}")),
|
||||||
|
None => Some("ADB 未发现该设备:USB 已拔出或 ADB 连接已断开".into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn parse(text: &str) -> Self {
|
||||||
|
Self::Devices(
|
||||||
|
text.lines()
|
||||||
|
.filter_map(|line| {
|
||||||
|
let mut fields = line.split_whitespace();
|
||||||
|
Some((fields.next()?.to_owned(), fields.next()?.to_owned()))
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Monitor {
|
||||||
|
pub receiver: watch::Receiver<Snapshot>,
|
||||||
|
task: JoinHandle<()>,
|
||||||
|
}
|
||||||
|
impl Monitor {
|
||||||
|
pub fn start(server: String) -> Self {
|
||||||
|
let (sender, receiver) = watch::channel(Snapshot::Pending);
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
// ads_core bounds connection and response reads to five seconds.
|
||||||
|
let next = match ads_core::adb_devices(&server).await {
|
||||||
|
Ok(text) => Snapshot::parse(&text),
|
||||||
|
Err(error) => Snapshot::Unavailable(format!("{error:#}")),
|
||||||
|
};
|
||||||
|
sender.send_if_modified(|current| {
|
||||||
|
if *current == next {
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
*current = next;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self { receiver, task }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Monitor {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.task.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn only_authorized_online_serials_are_available() {
|
||||||
|
let snapshot =
|
||||||
|
Snapshot::parse("ready\tdevice product:pixel\nlocked\tunauthorized\nlost\toffline\n");
|
||||||
|
assert!(snapshot.error_for("ready").is_none());
|
||||||
|
assert!(snapshot.error_for("locked").unwrap().contains("未授权"));
|
||||||
|
assert!(snapshot.error_for("lost").unwrap().contains("offline"));
|
||||||
|
assert!(snapshot.error_for("missing").unwrap().contains("未发现"));
|
||||||
|
assert!(Snapshot::Pending.error_for("ready").is_some());
|
||||||
|
assert!(Snapshot::Unavailable("stopped".into())
|
||||||
|
.error_for("ready")
|
||||||
|
.is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
+68
-8
@@ -6,6 +6,7 @@ use tracing::{info, warn};
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Gateway {
|
pub struct Gateway {
|
||||||
|
pub adb_presence: Option<tokio::sync::watch::Receiver<crate::adb_monitor::Snapshot>>,
|
||||||
pub network: NetworkArgs,
|
pub network: NetworkArgs,
|
||||||
pub token: String,
|
pub token: String,
|
||||||
pub device: String,
|
pub device: String,
|
||||||
@@ -62,7 +63,17 @@ async fn serve_session(
|
|||||||
relay(tcp, ws).await
|
relay(tcp, ws).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn probe_target(args: &Gateway) -> Result<()> {
|
||||||
|
if let Some(target) = &args.target {
|
||||||
|
let stream = tokio::time::timeout(Duration::from_secs(3), tcp_connect(target))
|
||||||
|
.await
|
||||||
|
.context("设备 TCP 连接检查超时")??;
|
||||||
|
drop(stream);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
async fn online(args: Arc<Gateway>, health: &Option<WorkerHealth>) -> Result<()> {
|
async fn online(args: Arc<Gateway>, health: &Option<WorkerHealth>) -> Result<()> {
|
||||||
|
probe_target(&args).await?;
|
||||||
let mut ws = dial(
|
let mut ws = dial(
|
||||||
args.network
|
args.network
|
||||||
.url("/v1/agent", &[("device", &args.device), ("v", "2")])?,
|
.url("/v1/agent", &[("device", &args.device), ("v", "2")])?,
|
||||||
@@ -81,6 +92,9 @@ async fn online(args: Arc<Gateway>, health: &Option<WorkerHealth>) -> Result<()>
|
|||||||
}
|
}
|
||||||
info!(device = %args.device, "gateway registered");
|
info!(device = %args.device, "gateway registered");
|
||||||
let mut tasks = JoinSet::new();
|
let mut tasks = JoinSet::new();
|
||||||
|
let mut target_check = tokio::time::interval(Duration::from_secs(5));
|
||||||
|
target_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
target_check.tick().await;
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
message = next_control(&mut ws) => {
|
message = next_control(&mut ws) => {
|
||||||
@@ -100,27 +114,73 @@ async fn online(args: Arc<Gateway>, health: &Option<WorkerHealth>) -> Result<()>
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
||||||
|
_ = target_check.tick(), if args.target.is_some() => {probe_target(&args).await?;},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// JoinSet drop aborts all streams when the control connection is lost.
|
// JoinSet drop aborts all streams when the control connection is lost.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn offline(health: &Option<WorkerHealth>, error: String) {
|
||||||
|
if let Some(health) = health {
|
||||||
|
let mut state = health.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
state.connected = false;
|
||||||
|
state.last_error = Some(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn wait_until_unavailable(
|
||||||
|
receiver: &mut tokio::sync::watch::Receiver<crate::adb_monitor::Snapshot>,
|
||||||
|
serial: &str,
|
||||||
|
) -> String {
|
||||||
|
loop {
|
||||||
|
let error = receiver.borrow_and_update().error_for(serial);
|
||||||
|
if let Some(error) = error {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
if receiver.changed().await.is_err() {
|
||||||
|
return "ADB 监听已停止".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
pub async fn run(args: Arc<Gateway>, health: Option<WorkerHealth>) {
|
pub async fn run(args: Arc<Gateway>, health: Option<WorkerHealth>) {
|
||||||
|
let mut presence = args.adb_presence.clone();
|
||||||
let mut delay = 1;
|
let mut delay = 1;
|
||||||
loop {
|
loop {
|
||||||
let started = std::time::Instant::now();
|
if let Some(receiver) = &mut presence {
|
||||||
if let Err(error) = online(args.clone(), &health).await {
|
loop {
|
||||||
if let Some(health) = &health {
|
let error = receiver
|
||||||
let mut state = health.lock().unwrap_or_else(|e| e.into_inner());
|
.borrow_and_update()
|
||||||
state.connected = false;
|
.error_for(args.adb_serial.as_deref().unwrap_or_default());
|
||||||
state.last_error = Some(format!("{error:#}"));
|
let Some(error) = error else { break };
|
||||||
|
offline(&health, error);
|
||||||
|
if receiver.changed().await.is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
warn!(device=%args.device,%error, "gateway offline; reconnecting");
|
}
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let result = if let Some(receiver) = &mut presence {
|
||||||
|
tokio::select! {
|
||||||
|
result=online(args.clone(),&health)=>result,
|
||||||
|
error=wait_until_unavailable(receiver,args.adb_serial.as_deref().unwrap_or_default())=>Err(anyhow::anyhow!(error)),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
online(args.clone(), &health).await
|
||||||
|
};
|
||||||
|
if let Err(error) = result {
|
||||||
|
offline(&health, format!("{error:#}"));
|
||||||
|
warn!(device=%args.device,%error,"gateway offline; reconnecting");
|
||||||
}
|
}
|
||||||
if started.elapsed() > Duration::from_secs(30) {
|
if started.elapsed() > Duration::from_secs(30) {
|
||||||
delay = 1;
|
delay = 1;
|
||||||
}
|
}
|
||||||
sleep(Duration::from_secs(delay)).await;
|
if let Some(receiver) = &mut presence {
|
||||||
|
tokio::select! {
|
||||||
|
_=sleep(Duration::from_secs(delay))=>{},
|
||||||
|
result=receiver.changed()=>{if result.is_err(){return;}delay=1;},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sleep(Duration::from_secs(delay)).await;
|
||||||
|
}
|
||||||
delay = (delay * 2).min(30);
|
delay = (delay * 2).min(30);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
mod adb_monitor;
|
||||||
mod gateway;
|
mod gateway;
|
||||||
mod managed;
|
mod managed;
|
||||||
mod supervisor;
|
mod supervisor;
|
||||||
@@ -69,7 +70,12 @@ async fn main() -> Result<()> {
|
|||||||
bail!("valid device and exactly one of --target / --adb-serial are required")
|
bail!("valid device and exactly one of --target / --adb-serial are required")
|
||||||
}
|
}
|
||||||
args.network.url("/v1/agent", &[])?;
|
args.network.url("/v1/agent", &[])?;
|
||||||
|
let monitor = args
|
||||||
|
.adb_serial
|
||||||
|
.as_ref()
|
||||||
|
.map(|_| adb_monitor::Monitor::start(args.adb_server.clone()));
|
||||||
let worker = gateway::Gateway {
|
let worker = gateway::Gateway {
|
||||||
|
adb_presence: monitor.as_ref().map(|m| m.receiver.clone()),
|
||||||
network: args.network,
|
network: args.network,
|
||||||
token,
|
token,
|
||||||
device,
|
device,
|
||||||
|
|||||||
+29
-1
@@ -78,6 +78,7 @@ struct State {
|
|||||||
config: AgentConfig,
|
config: AgentConfig,
|
||||||
workers: BTreeMap<String, Worker>,
|
workers: BTreeMap<String, Worker>,
|
||||||
revision: u64,
|
revision: u64,
|
||||||
|
monitors: BTreeMap<String, crate::adb_monitor::Monitor>,
|
||||||
}
|
}
|
||||||
struct Runtime {
|
struct Runtime {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
@@ -93,6 +94,25 @@ impl Runtime {
|
|||||||
fn reconcile(&self, state: &mut State) {
|
fn reconcile(&self, state: &mut State) {
|
||||||
let network = state.config.network();
|
let network = state.config.network();
|
||||||
let adb_server = state.config.adb_server.clone();
|
let adb_server = state.config.adb_server.clone();
|
||||||
|
let servers: std::collections::BTreeSet<_> = state
|
||||||
|
.config
|
||||||
|
.devices
|
||||||
|
.iter()
|
||||||
|
.filter(|device| device.enabled && device.adb_serial.is_some())
|
||||||
|
.map(|device| {
|
||||||
|
device
|
||||||
|
.adb_server
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| adb_server.clone())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
state.monitors.retain(|server, _| servers.contains(server));
|
||||||
|
for server in servers {
|
||||||
|
state
|
||||||
|
.monitors
|
||||||
|
.entry(server.clone())
|
||||||
|
.or_insert_with(|| crate::adb_monitor::Monitor::start(server));
|
||||||
|
}
|
||||||
state.workers.retain(|id, worker| {
|
state.workers.retain(|id, worker| {
|
||||||
state
|
state
|
||||||
.config
|
.config
|
||||||
@@ -106,6 +126,11 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
let health = Arc::new(Mutex::new(Health::default()));
|
let health = Arc::new(Mutex::new(Health::default()));
|
||||||
let gateway = Gateway {
|
let gateway = Gateway {
|
||||||
|
adb_presence: device.adb_serial.as_ref().map(|_| {
|
||||||
|
state.monitors[device.adb_server.as_ref().unwrap_or(&adb_server)]
|
||||||
|
.receiver
|
||||||
|
.clone()
|
||||||
|
}),
|
||||||
network: network.clone(),
|
network: network.clone(),
|
||||||
token: self.token.clone(),
|
token: self.token.clone(),
|
||||||
device: device.id.clone(),
|
device: device.id.clone(),
|
||||||
@@ -341,6 +366,7 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
|
|||||||
state: AsyncMutex::new(State {
|
state: AsyncMutex::new(State {
|
||||||
config,
|
config,
|
||||||
workers: BTreeMap::new(),
|
workers: BTreeMap::new(),
|
||||||
|
monitors: BTreeMap::new(),
|
||||||
revision: 1,
|
revision: 1,
|
||||||
}),
|
}),
|
||||||
token,
|
token,
|
||||||
@@ -380,6 +406,8 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
|
|||||||
};
|
};
|
||||||
tokio::pin!(networking);
|
tokio::pin!(networking);
|
||||||
let restart = tokio::select! {result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
|
let restart = tokio::select! {result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
|
||||||
runtime.state.lock().await.workers.clear();
|
let mut state = runtime.state.lock().await;
|
||||||
|
state.workers.clear();
|
||||||
|
state.monitors.clear();
|
||||||
Ok(restart)
|
Ok(restart)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using Ads.Desktop;
|
||||||
|
using Xunit;
|
||||||
|
namespace Ads.Desktop.Tests;
|
||||||
|
public class DevicePresenceTests {
|
||||||
|
[Fact] public void MissingRemoteDeviceDoesNotKeepOldReadyDescription() {
|
||||||
|
var item=new DeviceItem("phone",true,true,Online:false,LocalSummary:"ADB 就绪");
|
||||||
|
Assert.Contains("离线",item.Description);Assert.DoesNotContain("就绪",item.Description);
|
||||||
|
}
|
||||||
|
[Fact] public void AgentDeviceShowsUnavailableReason() {
|
||||||
|
var item=new ManagedDevice("phone",null,"USB-A",null,5555,true,false,"ADB 未发现该设备");
|
||||||
|
Assert.Contains("ADB 未发现",item.Description);Assert.DoesNotContain("已注册",item.Description);
|
||||||
|
}
|
||||||
|
[Fact] public void DisabledDeviceKeepsItsExplicitState() {
|
||||||
|
var item=new ManagedDevice("phone",null,"USB-A",null,5555,false,false,"ADB 未发现该设备");
|
||||||
|
Assert.Contains("已停用",item.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup><Version>0.2.5</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
<PropertyGroup><Version>0.2.6</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||||
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Semi.Avalonia" Version="11.3.7.3"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
|
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Semi.Avalonia" Version="11.3.7.3"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
|
||||||
<ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project>
|
<ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project>
|
||||||
@@ -12,7 +12,7 @@ public sealed record ManagedDevice(
|
|||||||
[property:JsonPropertyName("device_port")] int DevicePort, bool Enabled, bool Connected,
|
[property:JsonPropertyName("device_port")] int DevicePort, bool Enabled, bool Connected,
|
||||||
[property:JsonPropertyName("last_error")] string? LastError)
|
[property:JsonPropertyName("last_error")] string? LastError)
|
||||||
{
|
{
|
||||||
public string Description => $"{Id} · {(Enabled ? Connected ? LastError==null ? "已注册" : "转发异常" : "等待注册" : "已停用")} · {Target ?? AdbSerial}";
|
public string Description => $"{Id} · {(Enabled ? Connected ? LastError==null ? "已注册" : "转发异常:"+LastError : LastError==null ? "等待注册" : "未就绪:"+LastError : "已停用")} · {Target ?? AdbSerial}";
|
||||||
}
|
}
|
||||||
public sealed record ManagedStatus(string Id, string Name, string Hostname, string Os, string Arch, string Version, int Pid,
|
public sealed record ManagedStatus(string Id, string Name, string Hostname, string Os, string Arch, string Version, int Pid,
|
||||||
[property:JsonPropertyName("uptime_seconds")] long UptimeSeconds, bool Supervised, long Revision, string Instance, ManagedDevice[] Devices);
|
[property:JsonPropertyName("uptime_seconds")] long UptimeSeconds, bool Supervised, long Revision, string Instance, ManagedDevice[] Devices);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ namespace Ads.Desktop;
|
|||||||
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal, bool Online = true, string LocalSummary = "", string ComputerName="", string AgentId="")
|
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal, bool Online = true, string LocalSummary = "", string ComputerName="", string AgentId="")
|
||||||
{
|
{
|
||||||
public string ComputerLabel => "电脑:"+(ComputerName.Length==0?"未上报电脑名":ComputerName)+(AgentId.Length==0?"":" · "+AgentId);
|
public string ComputerLabel => "电脑:"+(ComputerName.Length==0?"未上报电脑名":ComputerName)+(AgentId.Length==0?"":" · "+AgentId);
|
||||||
public string Description => IsLocal ? "本机 · " + LocalSummary : !Online ? "远程暂时离线" : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
|
public string Description => !Online ? (IsLocal ? "远端离线 · 本机通道等待恢复" : "远程暂时离线") : IsLocal ? "本机 · " + LocalSummary : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
|
||||||
}
|
}
|
||||||
|
|
||||||
public partial class MainViewModel : ObservableObject, IDisposable
|
public partial class MainViewModel : ObservableObject, IDisposable
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
一个 `ads-agent --config` 进程管理一台电脑上的多部手机。`ads-server` 汇总所有 Agent,两套桌面客户端均提供“Agent 管理”:查看主机、选择手机、添加/移除/启用/停用、读取/应用配置、跟随日志、重启受监督 Agent。设备连接工作台继续使用同一组设备 ID。
|
一个 `ads-agent --config` 进程管理一台电脑上的多部手机。`ads-server` 汇总所有 Agent,两套桌面客户端均提供“Agent 管理”:查看主机、选择手机、添加/移除/启用/停用、读取/应用配置、跟随日志、重启受监督 Agent。设备连接工作台继续使用同一组设备 ID。
|
||||||
|
|
||||||
手机状态“已注册”表示设备转发工作线程已向控制中心注册,并不证明手机当前 ADB 在线;实际连接失败会显示转发错误。
|
手机状态“已注册”表示设备转发工作线程已向控制中心注册。0.2.6 起,使用 `adb_serial` 的设备必须出现在对应 ADB server 列表且状态为 `device` 才会注册;设备离线时显示具体原因。注册状态不保证手机上的 TCP ADB 端口或后续命令一定可用。
|
||||||
|
|
||||||
## 角色与连接
|
## 角色与连接
|
||||||
|
|
||||||
@@ -122,3 +122,14 @@ Windows 排障:本机管理返回拒绝访问时,检查配置目录所有者
|
|||||||
设备发现:两套客户端点击“发现 ADB 设备”,查询所选 Agent 主机的 ADB server,显示已添加、未添加、未授权/离线状态。选择在线且未添加的条目会填入添加表单,确认后添加;不自动暴露所有新插入的手机。CLI 使用 `adsctl devices discover`,远程可加 `--agent ID`。须先启动该主机的 ADB server;SYSTEM Agent 也通过配置的 TCP ADB server 地址查询。此能力需要控制中心与 Agent 更新到支持 devices_discover 的版本。
|
设备发现:两套客户端点击“发现 ADB 设备”,查询所选 Agent 主机的 ADB server,显示已添加、未添加、未授权/离线状态。选择在线且未添加的条目会填入添加表单,确认后添加;不自动暴露所有新插入的手机。CLI 使用 `adsctl devices discover`,远程可加 `--agent ID`。须先启动该主机的 ADB server;SYSTEM Agent 也通过配置的 TCP ADB server 地址查询。此能力需要控制中心与 Agent 更新到支持 devices_discover 的版本。
|
||||||
|
|
||||||
Linux 本机 Agent 初始没有配置时,先导入 agent.env 并初始化,再启动。桌面现在支持直接安装用户级 systemd 服务;无登录运行需管理员启用该用户 linger。新建私有配置目录使用 0700,以避免 Ubuntu 常见 umask 0002 创建组可写目录而被拒绝。已有目录不自动放宽权限。
|
Linux 本机 Agent 初始没有配置时,先导入 agent.env 并初始化,再启动。桌面现在支持直接安装用户级 systemd 服务;无登录运行需管理员启用该用户 linger。新建私有配置目录使用 0700,以避免 Ubuntu 常见 umask 0002 创建组可写目录而被拒绝。已有目录不自动放宽权限。
|
||||||
|
|
||||||
|
## 持续监听设备上下线(0.2.6)
|
||||||
|
|
||||||
|
Agent 对已配置且启用的 `adb_serial` 持续检查 ADB 列表,同一个 ADB server 共享一次查询。每次查询结束后等待 2 秒,连接及响应查询有 5 秒超时;正常情况下约 2 秒发现变化,ADB 无响应时还需等待查询超时。
|
||||||
|
|
||||||
|
- 设备消失、`offline`、`unauthorized` 或 ADB server 不可达:撤销该手机的控制中心注册,关闭旧数据流及租约;Agent 管理连接继续保留,显示未就绪原因。
|
||||||
|
- 手机重新在线并授权后:使用原设备 ID 自动注册,本地连接客户端可重新获取租约;不重启 Agent、不改写配置,不中断其他在线手机。
|
||||||
|
- 手动停用的设备保持停用。发现新插入的未配置设备仍需通过“发现 ADB 设备”或 CLI 添加,不会自动公开新手机。
|
||||||
|
- 使用 `target` 直连手机的配置不依赖本机 ADB 列表,注册前及每 5 秒检测 TCP 连接,单次检测超时 3 秒。TCP 可达仅表示端口可连接,不代表所有 ADB 命令必定成功。
|
||||||
|
|
||||||
|
工作台可能保留已建立的本地连接行,便于手机恢复后重连;该行会明确显示远端离线,不再沿用旧的 ADB 就绪提示。若 Agent 状态仍显示旧版本,请更新实际运行的守护程序,仅更新桌面 UI 不会替换已启动的 Agent。
|
||||||
@@ -101,3 +101,12 @@ Port cleanup follow-up:
|
|||||||
- Linux 包携带已验证的原生 ADB / scrcpy 5.0.1 完整发行资源及 LICENSE、Rust 四个 CLI 和应用菜单,检查 ELF 架构和动态库。六项隔离 dpkg 生命周期测试包含正式 Flutter deb、命令链接、CLI 版本和卸载回退。GUI 依赖由 apt 解析,完整 apt 仓库解析及 arm64 未在本轮实机验证。
|
- Linux 包携带已验证的原生 ADB / scrcpy 5.0.1 完整发行资源及 LICENSE、Rust 四个 CLI 和应用菜单,检查 ELF 架构和动态库。六项隔离 dpkg 生命周期测试包含正式 Flutter deb、命令链接、CLI 版本和卸载回退。GUI 依赖由 apt 解析,完整 apt 仓库解析及 arm64 未在本轮实机验证。
|
||||||
|
|
||||||
最终正式包验证在 Ubuntu 24.04 的临时 dpkg 根完成:6 项全部通过,包含随包 ADB/scrcpy 执行和 CLI 版本;正式 deb 解包后以 TT 普通用户在桌面会话启动 --package-check,输出 ADS_FLUTTER_PACKAGE_OK,退出 0。包声明 glibc >=2.35;本地旧 WSL 的 glibc 低于要求,因此随包 scrcpy 的执行验证转到目标 Ubuntu 完成,未放宽测试断言。
|
最终正式包验证在 Ubuntu 24.04 的临时 dpkg 根完成:6 项全部通过,包含随包 ADB/scrcpy 执行和 CLI 版本;正式 deb 解包后以 TT 普通用户在桌面会话启动 --package-check,输出 ADS_FLUTTER_PACKAGE_OK,退出 0。包声明 glibc >=2.35;本地旧 WSL 的 glibc 低于要求,因此随包 scrcpy 的执行验证转到目标 Ubuntu 完成,未放宽测试断言。
|
||||||
|
|
||||||
|
### 0.2.6:Agent 持续监听 ADB 上下线
|
||||||
|
|
||||||
|
- 新增 `tests/agent_adb_presence.py`,通过真实控制中心、Agent、客户端及可控 ADB smart socket 验证缺失、未授权、离线、ADB 服务失败/恢复和慢查询超时。验证一台手机断开不会中断另一台手机数据流,离线旧流关闭,恢复后可重新转发。
|
||||||
|
- 验证同一 ADB server 共享查询、管理 IPC 在慢查询时仍响应、Agent PID 与配置保持不变、设备 ID 保持不变、手动停用不会被自动恢复。原管理集成测试通过。
|
||||||
|
- Agent 状态解析单元测试通过,Avalonia 30 项测试及 Flutter 37 项测试通过,Flutter 静态分析无问题。两套 UI 显示未就绪原因并避免本地残留通道显示旧的在线状态。
|
||||||
|
- 本机 local-pc 已从 0.2.4 更新到 0.2.6,原程序备份在忽略的 work 目录,配置哈希保持一致。实测 ADB 列表为空时,Agent connected=false 并显示“ADB 未发现该设备”,管理 IPC 持续可用;本轮未要求插拔真实手机,恢复路径由真实三端集成测试覆盖。
|
||||||
|
- 0.2.6 Windows Avalonia/Flutter Setup 与 Linux Agent/Avalonia/Flutter deb 已生成。Windows Avalonia 正式包启动检查通过;Linux Flutter 原生静态分析及 37 项测试通过,Linux Agent/Avalonia 正式 deb 的 6 项临时根安装/卸载测试通过。
|
||||||
|
- Ubuntu 24.04 对正式 Flutter/Agent deb 的 6 项隔离安装测试通过;正式 Flutter deb 解包后在真实桌面会话执行 --package-check,输出 ADS_FLUTTER_PACKAGE_OK 并退出 0。
|
||||||
@@ -26,8 +26,10 @@ abstract class ManagedPhone with _$ManagedPhone {
|
|||||||
: connected
|
: connected
|
||||||
? lastError == null
|
? lastError == null
|
||||||
? "已注册"
|
? "已注册"
|
||||||
: "转发异常"
|
: "转发异常:$lastError"
|
||||||
: "等待注册"} · ${target ?? adbSerial ?? ""}';
|
: lastError == null
|
||||||
|
? "等待注册"
|
||||||
|
: "未就绪:$lastError"} · ${target ?? adbSerial ?? ""}';
|
||||||
}
|
}
|
||||||
|
|
||||||
@freezed
|
@freezed
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 0.2.5+6
|
version: 0.2.6+7
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.14.0
|
sdk: ^3.14.0
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:ads_manager/data/agent_models.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('unregistered phone shows its ADB absence reason', () {
|
||||||
|
const phone = ManagedPhone(
|
||||||
|
id: 'phone',
|
||||||
|
adbSerial: 'USB-A',
|
||||||
|
enabled: true,
|
||||||
|
connected: false,
|
||||||
|
lastError: 'ADB 未发现该设备',
|
||||||
|
);
|
||||||
|
expect(phone.description, contains('ADB 未发现'));
|
||||||
|
expect(phone.description, isNot(contains('已注册')));
|
||||||
|
});
|
||||||
|
test('disabled phone remains explicitly disabled', () {
|
||||||
|
const phone = ManagedPhone(
|
||||||
|
id: 'phone',
|
||||||
|
enabled: false,
|
||||||
|
connected: false,
|
||||||
|
lastError: 'offline',
|
||||||
|
);
|
||||||
|
expect(phone.description, contains('已停用'));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
"""Real controller/agent regression with a controllable ADB smart socket server."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import socketserver
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from e2e import ROOT, free_port, wait_until, Echo, Phone
|
||||||
|
|
||||||
|
|
||||||
|
def receive(stream, size):
|
||||||
|
data = b''
|
||||||
|
while len(data) < size:
|
||||||
|
chunk = stream.recv(size-len(data))
|
||||||
|
if not chunk:
|
||||||
|
raise EOFError('ADB socket closed')
|
||||||
|
data += chunk
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class AdbHandler(socketserver.BaseRequestHandler):
|
||||||
|
def handle(self):
|
||||||
|
try:
|
||||||
|
self.request.settimeout(15)
|
||||||
|
service = receive(self.request, int(receive(self.request, 4), 16)).decode()
|
||||||
|
with self.server.lock:
|
||||||
|
available = self.server.available
|
||||||
|
devices = dict(self.server.devices)
|
||||||
|
if service == 'host:devices-l':
|
||||||
|
self.server.queries += 1
|
||||||
|
delay = self.server.delay
|
||||||
|
self.server.queried.set()
|
||||||
|
else:
|
||||||
|
delay = 0
|
||||||
|
if not available:
|
||||||
|
return
|
||||||
|
if delay:
|
||||||
|
time.sleep(delay)
|
||||||
|
if service == 'host:devices-l':
|
||||||
|
text = ''.join(f'{serial}\t{state} product:test\n' for serial, state in devices.items()).encode()
|
||||||
|
self.request.sendall(b'OKAY'+f'{len(text):04x}'.encode()+text)
|
||||||
|
return
|
||||||
|
serial = service.removeprefix('host:transport:')
|
||||||
|
if not service.startswith('host:transport:') or devices.get(serial) != 'device':
|
||||||
|
self.request.sendall(b'FAIL0007offline')
|
||||||
|
return
|
||||||
|
self.request.sendall(b'OKAY')
|
||||||
|
service = receive(self.request, int(receive(self.request, 4), 16))
|
||||||
|
if service != b'tcp:5555':
|
||||||
|
return
|
||||||
|
self.request.sendall(b'OKAY')
|
||||||
|
while data := self.request.recv(65536):
|
||||||
|
self.request.sendall(data)
|
||||||
|
except (OSError, EOFError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Adb(socketserver.ThreadingTCPServer):
|
||||||
|
allow_reuse_address = True
|
||||||
|
daemon_threads = True
|
||||||
|
block_on_close = False
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__(('127.0.0.1', 0), AdbHandler)
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.devices = {}
|
||||||
|
self.available = True
|
||||||
|
self.delay = 0
|
||||||
|
self.queries = 0
|
||||||
|
self.queried = threading.Event()
|
||||||
|
|
||||||
|
def set(self, devices=None, available=None, delay=None):
|
||||||
|
with self.lock:
|
||||||
|
if devices is not None:
|
||||||
|
self.devices = devices
|
||||||
|
if available is not None:
|
||||||
|
self.available = available
|
||||||
|
if delay is not None:
|
||||||
|
self.delay = delay
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--rust-dir', type=Path, default=ROOT/'target/debug')
|
||||||
|
parser.add_argument('--bin-dir', type=Path, default=ROOT/'bin')
|
||||||
|
args = parser.parse_args()
|
||||||
|
suffix = '.exe' if os.name == 'nt' else ''
|
||||||
|
folder = ROOT/'work/agent-adb-presence'/uuid.uuid4().hex
|
||||||
|
folder.mkdir(parents=True, mode=0o700)
|
||||||
|
config = folder/'agent.json'
|
||||||
|
tokens = {key: secrets.token_hex(32) for key in ('ADS_AGENT_TOKEN', 'ADS_CLIENT_TOKEN', 'ADS_ADMIN_TOKEN')}
|
||||||
|
port = free_port()
|
||||||
|
url = f'ws://127.0.0.1:{port}'
|
||||||
|
processes, logs = [], []
|
||||||
|
|
||||||
|
def environment(*roles):
|
||||||
|
result = dict(os.environ)
|
||||||
|
for key in (*tokens, 'ADS_CONNECT_ADDRESS'):
|
||||||
|
result.pop(key, None)
|
||||||
|
result.update({key: tokens[key] for key in roles})
|
||||||
|
result['RUST_LOG'] = 'ads_agent=info,ads_core=info,warn'
|
||||||
|
return result
|
||||||
|
|
||||||
|
def launch(name, command, *roles):
|
||||||
|
output = open(folder/(name+'.log'), 'wb')
|
||||||
|
logs.append(output)
|
||||||
|
process = subprocess.Popen(list(map(str, command)), env=environment(*roles), stdout=output, stderr=output,
|
||||||
|
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
||||||
|
processes.append(process)
|
||||||
|
return process
|
||||||
|
|
||||||
|
def get(path, role='ADS_CLIENT_TOKEN'):
|
||||||
|
request = urllib.request.Request(url.replace('ws:', 'http:')+path, headers={'Authorization':'Bearer '+tokens[role]})
|
||||||
|
with urllib.request.urlopen(request, timeout=3) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
def cli(*commands):
|
||||||
|
result = subprocess.run([str(args.rust_dir/('adsctl'+suffix)), '--json', '--config', str(config), *commands],
|
||||||
|
env=environment(), capture_output=True, text=True, encoding='utf-8', timeout=8)
|
||||||
|
assert result.returncode == 0, result.stderr
|
||||||
|
return json.loads(result.stdout)
|
||||||
|
|
||||||
|
def listed():
|
||||||
|
return {device['id'] for device in get('/v1/devices')}
|
||||||
|
|
||||||
|
with Adb() as adb, Phone(('127.0.0.1', 0), Echo) as direct:
|
||||||
|
for server in (adb, direct):
|
||||||
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||||
|
try:
|
||||||
|
config.write_text(json.dumps({'version':1, 'id':'presence-test', 'name':'ADB presence test', 'server':url,
|
||||||
|
'allow_insecure':True, 'adb_server':f'127.0.0.1:{adb.server_address[1]}', 'devices':[
|
||||||
|
{'id':'phone-a', 'adb_serial':'USB-A'}, {'id':'phone-b', 'adb_serial':'USB-B'},
|
||||||
|
{'id':'direct-phone', 'target':f'127.0.0.1:{direct.server_address[1]}'}]}, indent=2), encoding='utf-8')
|
||||||
|
config.chmod(0o600)
|
||||||
|
original = config.read_bytes()
|
||||||
|
launch('controller', [args.bin_dir/('ads-server'+suffix), '--listen', f'127.0.0.1:{port}'], *tokens)
|
||||||
|
wait_until(lambda: get('/v1/devices') == [], 'controller startup')
|
||||||
|
started = time.monotonic()
|
||||||
|
launch('agent', [args.rust_dir/('ads-agent'+suffix), '--config', config], 'ADS_AGENT_TOKEN')
|
||||||
|
wait_until(lambda: listed() == {'direct-phone'}, 'initial missing ADB devices are not registered')
|
||||||
|
pid = cli('status')['pid']
|
||||||
|
adb.set({'USB-A':'device', 'USB-B':'unauthorized'})
|
||||||
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'only authorized device registered')
|
||||||
|
status = cli('status')
|
||||||
|
assert any(d['id']=='phone-b' and not d['connected'] and '未授权' in d['last_error'] for d in status['devices'])
|
||||||
|
adb.set({'USB-A':'device', 'USB-B':'device'})
|
||||||
|
wait_until(lambda: len(listed()) == 3, 'second device authorized')
|
||||||
|
|
||||||
|
client_port = free_port()
|
||||||
|
launch('client', [args.rust_dir/('ads-client'+suffix), '--server', url, '--allow-insecure', '--device', 'phone-a',
|
||||||
|
'--listen', f'127.0.0.1:{client_port}', '--transport', 'relay', '--no-auto-connect'], 'ADS_CLIENT_TOKEN')
|
||||||
|
wait_until(lambda: any(d['id']=='phone-a' and d['busy'] for d in get('/v1/devices')), 'client lease')
|
||||||
|
with socket.create_connection(('127.0.0.1', client_port), timeout=5) as stream:
|
||||||
|
stream.settimeout(8)
|
||||||
|
stream.sendall(b'before')
|
||||||
|
assert receive(stream, 6) == b'before'
|
||||||
|
adb.set({'USB-A':'device'})
|
||||||
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'unplug removes only second device')
|
||||||
|
stream.sendall(b'after')
|
||||||
|
assert receive(stream, 5) == b'after'
|
||||||
|
adb.set({'USB-A':'offline', 'USB-B':'device'})
|
||||||
|
wait_until(lambda: listed() == {'direct-phone', 'phone-b'}, 'offline state unregisters first device')
|
||||||
|
try:
|
||||||
|
assert stream.recv(1) == b'', 'offline upstream connection was retained'
|
||||||
|
except ConnectionResetError:
|
||||||
|
pass
|
||||||
|
assert cli('status')['pid'] == pid
|
||||||
|
assert config.read_bytes() == original, 'monitor rewrote configuration or IDs'
|
||||||
|
adb.set(available=False)
|
||||||
|
wait_until(lambda: listed() == {'direct-phone'}, 'ADB server failure withdraws all serial devices')
|
||||||
|
assert any(a['online'] for a in get('/v3/agents', 'ADS_ADMIN_TOKEN')), 'Agent management went offline'
|
||||||
|
adb.set({'USB-A':'device', 'USB-B':'device'}, available=True)
|
||||||
|
wait_until(lambda: len(listed()) == 3, 'ADB server recovery restores original IDs')
|
||||||
|
def recovered_stream():
|
||||||
|
try:
|
||||||
|
with socket.create_connection(('127.0.0.1', client_port), timeout=2) as stream:
|
||||||
|
stream.settimeout(2)
|
||||||
|
stream.sendall(b'recovered')
|
||||||
|
return receive(stream, 9) == b'recovered'
|
||||||
|
except (OSError, EOFError):
|
||||||
|
return False
|
||||||
|
wait_until(recovered_stream, 'client reacquires lease and forwards after recovery')
|
||||||
|
elapsed = time.monotonic()-started
|
||||||
|
assert adb.queries <= elapsed/2+3, 'ADB polling was duplicated per phone'
|
||||||
|
cli('devices', 'disable', 'phone-b')
|
||||||
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'disabled device withdrawn')
|
||||||
|
time.sleep(2.5)
|
||||||
|
assert 'phone-b' not in listed(), 'monitor re-enabled a disabled device'
|
||||||
|
adb.queried.clear()
|
||||||
|
adb.set(delay=8)
|
||||||
|
assert adb.queried.wait(4), 'delayed ADB query did not start'
|
||||||
|
request_started = time.monotonic()
|
||||||
|
assert cli('status')['pid'] == pid
|
||||||
|
assert time.monotonic()-request_started < 3, 'ADB query blocked management IPC'
|
||||||
|
wait_until(lambda: listed() == {'direct-phone'}, 'hung ADB query expires')
|
||||||
|
adb.set(delay=0)
|
||||||
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'query timeout recovery respects disabled device')
|
||||||
|
print('PASS: missing/offline/unauthorized/server failure withdraw registration; recovery preserves IDs and PID')
|
||||||
|
print('PASS: one poll per ADB server; other phone stream stays live; old stream closes and reconnects; disabled stays disabled')
|
||||||
|
finally:
|
||||||
|
for process in reversed(processes):
|
||||||
|
if process.poll() is None:
|
||||||
|
process.terminate()
|
||||||
|
process.wait(timeout=10)
|
||||||
|
for output in logs:
|
||||||
|
output.close()
|
||||||
|
adb.shutdown()
|
||||||
|
direct.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user