//! 大腦管理員 (`anybot --brains`, deploy/server's `brains` service): every account on this //! server's account server gets a cloud brain of its own — signed up from the app, it is there a //! few seconds later, with nothing to set on the server. One container a brain //! (`anybot-brain-`): the same image, its own data volume, `restart: unless-stopped` //! (back after a reboot), signed in with a host token the account server hands the manager //! (`/relay/manager/brain`): no password is kept on the server. //! //! An account holder runs commands on their brain (hooks, connectors). So: //! - Docker is the whole server: only the owner's brain (the first account, kept once seen) and //! the accounts named in ANYBOT_BRAINS_DOCKER get it (through the filtered proxy, their own box //! and its home volume); the others work on their own computers. //! - No brain may forge or overhear traffic on the network it shares with the account server //! (no NET_RAW, no new privileges), and the manager talks to the account server on a network of //! its own (its key never crosses the brains' one); each brain has a memory and process limit. //! //! Accounts made before the manager first ran (an older server updated) are left as they were: //! they have their own brains already. ANYBOT_BRAINS_ALL=1 gives them one too. //! //! A brain from an older image or other settings (after `make update-server`) is made again with //! the same volume and sign-in, after it is let to finish (stopped, not killed); one whose sign-in //! the account server no longer has gets a new one. The manager never removes a brain's data. use serde_json::{json, Value}; use std::collections::HashMap; use std::process::Command; use std::time::{Duration, Instant}; /// What the manager starts brains with. #[derive(Clone, Debug, Default, PartialEq)] pub struct Config { /// The account server as the manager reaches it (its own network): http://relay-manager:8080. pub relay: String, /// The account server as the brains reach it: http://relay:8080. pub brain_relay: String, pub key: String, /// The image the brains run (the manager's own: one build for both). pub image: String, /// The account server's network (every brain) and Docker's proxy's (only brains with Docker). pub network: String, pub docker_network: Option, /// Accounts left alone: the older single-account setup's own brain (ANYBOT_USER) runs as /// before, as the compose file's `anybot`. pub skip: Vec, /// Accounts whose brains get Docker besides the owner's (ANYBOT_BRAINS_DOCKER). pub docker_users: Vec, /// Accounts made before this (seconds): left alone, unless `all`. pub since: i64, pub all: bool, /// Each brain's memory limit (docker's form: 4g; no swap beyond it) and CPUs (2). pub memory: String, /// None: this Docker can't hold a container to a share of the CPUs (no CFS quota — rootless /// without the cpu controller), where `--cpus` is refused and no brain could be made. pub cpus: Option, /// At most this many cloud brains (one invite can sign up many accounts). pub max: usize, /// Passed on to every brain as it is (語音, the model mirror). pub env: Vec<(String, String)>, /// Passed on only to brains with Docker (DOCKER_HOST: the proxy). pub docker_env: Vec<(String, String)>, } /// An account as the account server lists it: its name and when it was made (seconds). #[derive(Clone, Debug, PartialEq)] pub struct Account { pub name: String, pub created: i64, } /// One account's brain container as Docker has it. #[derive(Clone, Debug, Default, PartialEq)] pub struct Existing { pub name: String, pub running: bool, /// What its image holds (a hash of the image's layers — the image ID changes with every /// build, even one that changed nothing), whether it was given Docker, the hash of how it was /// made (create_args without its sign-in), and the account server's id for it. pub image: String, pub docker: bool, pub args: String, pub host: String, /// The networks it is on, joined with `,` (its way to Docker is one of them). pub networks: String, } #[derive(Clone, Debug, PartialEq)] pub enum Action { /// A brain made before, not running (stopped by hand, or its start failed): start it — joined to /// Docker's network first when it has Docker (a manager stopped between making and joining /// left the owner's brain without it). Start(String, bool), /// An account with no brain yet: make one (with Docker or not). Create(String, bool), /// A brain from an older image or other settings: made again with the same volume — and the /// same sign-in, or (true) a new one when the account server no longer has its. Remake(String, bool, bool), } /// Whether this account's brain gets Docker: the owner's and the ones named. pub fn gets_docker(user: &str, owner: Option<&str>, named: &[String]) -> bool { owner == Some(user) || named.iter().any(|n| n.eq_ignore_ascii_case(user)) } /// The brains that count toward ANYBOT_BRAINS_MAX: not the ones stopped on purpose (skipped). fn counted(existing: &HashMap, c: &Config) -> usize { existing.keys().filter(|u| !c.skip.iter().any(|s| s.eq_ignore_ascii_case(u))).count() } /// The server's owner: the first account made (kept by the manager once it has seen it — a /// clock set back, an account taken away, never hands Docker to another). pub fn first_account(accounts: &[Account]) -> Option<&str> { accounts.iter().min_by_key(|a| a.created).map(|a| a.name.as_str()) } /// What to do for each account. `managed`: the account server's id of the brain it knows for /// each account (None: an older account server that doesn't say). pub fn plan(accounts: &[Account], existing: &HashMap, image: &str, owner: Option<&str>, managed: Option<&HashMap>, c: &Config) -> Vec { let mut out = vec![]; // (At most `max` brains: the ones there and the ones about to be made.) let mut room = c.max.saturating_sub(counted(existing, c)); for a in accounts { let u = &a.name; if c.skip.iter().any(|s| s.eq_ignore_ascii_case(u)) { continue; } let docker = gets_docker(u, owner, &c.docker_users); match existing.get(u) { Some(e) => { // (Its sign-in gone from the account server: removed, an older data file.) let lost = managed.is_some_and(|m| !e.host.is_empty() && m.get(u) != Some(&e.host)); let stale = (!image.is_empty() && e.image != image) || e.docker != docker || e.args != args_hash(u, docker, c); if lost || stale { out.push(Action::Remake(u.clone(), docker, lost)); } else if !e.running { out.push(Action::Start(e.name.clone(), docker)); } } // (An account from before the manager: its own brain is elsewhere.) None if a.created < c.since && !c.all => {} None if room == 0 => {} None => { room -= 1; out.push(Action::Create(u.clone(), docker)); } } } // A new account's brain first (someone is waiting for it), the updates last. out.sort_by_key(|a| match a { Action::Create(..) => 0, Action::Start(..) => 1, Action::Remake(..) => 2, }); out } /// An account name as a Docker name: letters, digits and - (a name of `.`, `_` or `@` keeps /// apart from another by a short hash of the whole name). pub fn slug(user: &str) -> String { let mut s: String = user.to_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); while s.contains("--") { s = s.replace("--", "-"); } let s: String = s.trim_matches('-').chars().take(30).collect(); let hash = crate::httpd::sha256_hex(user); format!("{}-{}", if s.is_empty() { "user" } else { s.trim_end_matches('-') }, &hash[..6]) } pub fn container_name(user: &str) -> String { format!("anybot-brain-{}", slug(user)) } /// How a brain is made, but its sign-in: what decides whether one made earlier is still right. fn base_args(user: &str, docker: bool, c: &Config) -> Vec { let s = slug(user); let mut a: Vec = ["--restart", "unless-stopped"].iter().map(|x| x.to_string()).collect(); a.extend(["--name".into(), container_name(user)]); a.extend(["--label".into(), format!("anybot.brain.user={user}")]); a.extend(["--label".into(), format!("anybot.brain.docker={}", if docker { 1 } else { 0 })]); a.extend(["-v".into(), format!("anybot-brain-{s}:/data")]); a.extend(["--network".into(), c.network.clone()]); // Commands run here are the account holder's: no forging or overhearing on the network shared // with the account server, no gaining privileges, and a share of the machine only. a.extend(["--cap-drop".into(), "NET_RAW".into(), "--security-opt".into(), "no-new-privileges".into()]); a.extend(["--pids-limit".into(), "2048".into(), "--memory".into(), c.memory.clone(), "--memory-swap".into(), c.memory.clone()]); if let Some(n) = &c.cpus { a.extend(["--cpus".into(), n.clone()]); } let mut env: Vec<(String, String)> = vec![("ANYBOT_ACCOUNT".into(), format!("{}|{user}", c.brain_relay)), ("ANYBOT_HOST_NAME".into(), "雲端大腦".into())]; if docker { // Its own bots' computer and that computer's home: never another account's files. env.push(("ANYBOT_BOX_NAME".into(), format!("anybot-box-{s}"))); env.push(("ANYBOT_BOX_VOLUME".into(), format!("anybot-box-home-{s}"))); env.extend(c.docker_env.iter().cloned()); } env.extend(c.env.iter().cloned()); for (k, v) in env { a.extend(["-e".into(), format!("{k}={v}")]); } a } pub fn args_hash(user: &str, docker: bool, c: &Config) -> String { let mut all = base_args(user, docker, c); all.push(c.image.clone()); crate::httpd::sha256_hex(&all.join("\u{1f}"))[..16].to_string() } /// The `docker create` arguments of an account's brain (started after its networks are joined). /// `holds`: what the image holds (layers()), kept as a label — the image it was made from can't be /// looked at once a rebuild has moved the name on (Docker's containerd store: "No such image"). pub fn create_args(user: &str, host_id: &str, host_token: &str, docker: bool, holds: &str, c: &Config) -> Vec { let mut a = vec!["create".to_string()]; a.extend(base_args(user, docker, c)); a.extend(["--label".into(), format!("anybot.brain.args={}", args_hash(user, docker, c))]); a.extend(["--label".into(), format!("anybot.brain.layers={holds}")]); a.extend(["--label".into(), format!("anybot.brain.host={host_id}")]); a.extend(["-e".into(), format!("ANYBOT_HOST_ID={host_id}"), "-e".into(), format!("ANYBOT_HOST_TOKEN={host_token}")]); a.push(c.image.clone()); a.extend(["anybot".into(), "--serve".into()]); a } /// `anybot --brains`: the manager, until stopped. pub fn run() -> ! { let cfg = match config() { Ok(c) => c, Err(e) => { log::warn!("AnyBot 大腦管理員:{e}"); std::process::exit(2); } }; log::info!("AnyBot 大腦管理員:每個帳號一個雲端大腦(映像 {},網路 {})", cfg.image, cfg.network); // A stop (docker compose stop / an update) ends it after the job under way. let _ = ctrlc::set_handler(|| STOPPING.store(true, std::sync::atomic::Ordering::SeqCst)); let mut said = String::new(); // Accounts whose last tries failed, and how many times in a row: tried again a minute later, // then two, four… up to half an hour (each try asks for a sign-in, and a remake stops the // brain that runs). let mut resting: HashMap = HashMap::new(); loop { let errors = tick(&cfg, &mut resting); // (Said once until it changes: an account server still starting would fill the log.) let now = errors.join(";"); if now != said { if !now.is_empty() { log::warn!("AnyBot 大腦管理員:{now}"); } said = now; } for _ in 0..50 { if STOPPING.load(std::sync::atomic::Ordering::SeqCst) { log::info!("AnyBot 大腦管理員:停止"); std::process::exit(0); } std::thread::sleep(Duration::from_millis(100)); } } } static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// The owner, kept in the manager's data folder the first time there is one. fn owner(accounts: &[Account]) -> Option { let file = data_folder().join("brains-owner"); if let Some(o) = std::fs::read_to_string(&file).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) { return Some(o); } let first = first_account(accounts)?.to_string(); let _ = std::fs::write(&file, &first); log::info!("AnyBot 大腦管理員:擁有者是 {first}(它的雲端大腦有 Bot 的電腦)"); Some(first) } /// How long an account rests after this many failed tries in a row. fn rest_for(fails: u32) -> Duration { Duration::from_secs((60u64 << fails.saturating_sub(1).min(5)).min(30 * 60)) } fn tick(cfg: &Config, resting: &mut HashMap) -> Vec { let (accounts, managed) = match accounts(cfg) { Ok(a) => a, Err(e) => return vec![e], }; let existing = match existing() { Ok(e) => e, Err(e) => return vec![e], }; let image = layers(&cfg.image); let owner = owner(&accounts); let mut errors = vec![]; let waiting = accounts.iter().filter(|a| !existing.contains_key(&a.name) && !cfg.skip.iter().any(|s| s.eq_ignore_ascii_case(&a.name)) && (a.created >= cfg.since || cfg.all)).count(); if counted(&existing, cfg) + waiting > cfg.max { errors.push(format!("雲端大腦已經 {} 個,到上限(ANYBOT_BRAINS_MAX={}):新的帳號先不開", counted(&existing, cfg), cfg.max)); } // Docker as it is set now, every time: a brain on the way to it only when it gets Docker now // and was made with it — taken away at once (not when it is made again, which can keep // failing), given back when it was lost, never given to one made without it (one put back or // woken after a failed remake). if let Some(n) = &cfg.docker_network { for (u, e) in &existing { let want = e.docker && gets_docker(u, owner.as_deref(), &cfg.docker_users); if want != on_network(e, n) && docker(&["network", if want { "connect" } else { "disconnect" }, n, &e.name]).is_ok() { log::info!("AnyBot 大腦管理員:{u} 的雲端大腦{}", if want { "接回 Docker" } else { "拿掉 Docker" }); } } } let actions = plan(&accounts, &existing, &image, owner.as_deref(), managed.as_ref(), cfg); let who = |a: &Action| match a { Action::Start(n, _) => n.clone(), Action::Create(u, _) | Action::Remake(u, _, _) => u.clone(), }; // (One with nothing left to do starts afresh the next time it has something.) resting.retain(|w, _| actions.iter().any(|a| &who(a) == w)); // Each on its own: one that fails doesn't keep the others from their brains. for (i, a) in actions.into_iter().enumerate() { // (Stopping: after the job under way, never in the middle of one.) if STOPPING.load(std::sync::atomic::Ordering::SeqCst) { break; } // (Asked again between long jobs — remaking many brains takes minutes: the account server // keeps saying brains are made, and a sign-up meanwhile still waits for its own.) if i > 0 { let _ = self::accounts(cfg); } let who = who(&a); if resting.get(&who).is_some_and(|(t, n)| t.elapsed() < rest_for(*n)) { continue; } let r = match &a { Action::Start(name, d) => { log::info!("AnyBot 大腦管理員:叫醒 {name}"); if *d { if let Some(n) = &cfg.docker_network { // (Already joined: Docker says so, and that is fine.) let _ = docker(&["network", "connect", n, name]); } } docker(&["start", name]).map(|_| ()) } Action::Create(user, d) => create(cfg, user, *d, None), Action::Remake(user, d, fresh) => remake(cfg, user, *d, *fresh), }; match r { Err(e) => { let n = resting.get(&who).map_or(0, |r| r.1) + 1; resting.insert(who, (Instant::now(), n)); errors.push(e); } Ok(()) => { resting.remove(&who); } } } errors } /// Made again: the same volume, and the same sign-in read back from the old container (no new /// token, nothing else of the account changes) — or a new one when that one is gone. Stopped /// first, so a turn under way is ended the way a stop ends it, its work saved. fn remake(cfg: &Config, user: &str, d: bool, fresh: bool) -> Result<(), String> { let name = container_name(user); let r = remake_beside(cfg, user, d, fresh, &name); if r.is_err() { // Not made again: the brain there runs. One found stopped (the manager stopped half way // through an earlier remake, after the old one was stopped) was planned only to be made // again — not woken — and would stay stopped while every try fails. if docker(&["inspect", "-f", "{{.State.Running}}", &name]).is_ok_and(|s| s.trim() == "false") { docker_access(cfg, &name, d); if docker(&["start", &name]).is_ok() { log::info!("AnyBot 大腦管理員:{user} 原本的雲端大腦停著,先叫醒它"); } } } r } /// Docker taken away before an old brain is put back or woken: it keeps the networks it had. /// (Never joined here — whether it was made with Docker isn't known here; the next tick joins /// the one that should be.) fn docker_access(cfg: &Config, name: &str, d: bool) { if let (false, Some(n)) = (d, &cfg.docker_network) { let _ = docker(&["network", "disconnect", n, name]); } } /// Whether it is on that network. pub fn on_network(e: &Existing, network: &str) -> bool { e.networks.split(',').any(|x| x.trim() == network) } fn remake_beside(cfg: &Config, user: &str, d: bool, fresh: bool, name: &str) -> Result<(), String> { let name = name.to_string(); // (Its sign-in read back — when Docker doesn't answer, nothing is done: a new sign-in would // sign the running brain out, and it would stay so if the rest then failed.) let sign_in = if fresh { None } else { let env = docker(&["inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", &name]).map_err(|e| format!("讀不到 {user} 雲端大腦的登入,先不換:{e}"))?; let val = |k: &str| env.lines().find_map(|l| l.strip_prefix(&format!("{k}=")).map(String::from)).filter(|v| !v.is_empty()); val("ANYBOT_HOST_ID").zip(val("ANYBOT_HOST_TOKEN")) }; // A new sign-in, if one is needed, before the old brain is touched (a refusal touches nothing). let (id, token) = match sign_in { Some(s) => s, None => issue(cfg, user)?, }; // Made beside the running one, under a name of its own: Docker checks everything when making // a container, so one it refuses (a limit it won't take, a full disk) leaves the old brain // running, untouched — it used to be stopped and started again every try. let new = format!("{name}-new"); let aside = format!("{name}-old"); let _ = docker(&["rm", "-f", &new]); let mut args = create_args(user, &id, &token, d, &layers(&cfg.image), cfg); if let Some(i) = args.iter().position(|a| a == "--name") { args[i + 1] = new.clone(); } let a: Vec<&str> = args.iter().map(String::as_str).collect(); let made = docker(&a).and_then(|_| match (d, &cfg.docker_network) { (true, Some(n)) => docker(&["network", "connect", n, &new]), _ => Ok(String::new()), }); if let Err(e) = made { let _ = docker(&["rm", "-f", &new]); return Err(format!("{user} 的新版雲端大腦開不起來,原本的照常在跑:{e}")); } // Then the swap: the old one stopped (its turn ended the way a stop ends it), put aside, the // new one under its name and started; the old one gone only once the new one runs. // (The name it goes aside under is free first: one left there would keep the swap from // happening only after the old one was stopped.) let _ = docker(&["rm", "-f", &aside]); if docker(&["inspect", "-f", "{{.Id}}", &aside]).is_ok() { let _ = docker(&["rm", "-f", &new]); return Err(format!("{user} 旁邊還有一個換下來的雲端大腦({aside})拿不掉,先不換")); } // (Gone on only when Docker says it stopped: a stop that failed and an answer that didn't // come are both 「not sure」, and a running brain is never renamed under its own turn.) let stopped = |n: &str| docker(&["inspect", "-f", "{{.State.Running}}", n]).is_ok_and(|s| s.trim() == "false"); if docker(&["stop", "-t", "30", &name]).is_err() && !stopped(&name) { let _ = docker(&["rm", "-f", &new]); return Err(format!("{user} 原本的雲端大腦停不下來,先不換")); } log::info!("AnyBot 大腦管理員:{user} 的雲端大腦{}", if fresh { "登入不在了,換一個新的" } else { "換成新版" }); let back = |why: String| { let _ = docker(&["rm", "-f", &name]); let _ = docker(&["rename", &aside, &name]); docker_access(cfg, &name, d); let _ = docker(&["start", &name]); let _ = docker(&["rm", "-f", &new]); Err(format!("{user} 的新版雲端大腦開不起來,先用原本的:{why}")) }; if let Err(e) = docker(&["rename", &name, &aside]) { docker_access(cfg, &name, d); let _ = docker(&["start", &name]); let _ = docker(&["rm", "-f", &new]); return Err(format!("{user} 的雲端大腦換不了:{e}")); } if let Err(e) = docker(&["rename", &new, &name]) { return back(e); } if let Err(e) = docker(&["start", &name]) { return back(e); } let _ = docker(&["rm", "-f", &aside]); log::info!("AnyBot 大腦管理員:{user} 的雲端大腦開好了({name}{})", if d { ",有 Bot 的電腦" } else { "" }); Ok(()) } /// A cloud brain's sign-in from the account server (a new host token for 「雲端大腦」). fn issue(cfg: &Config, user: &str) -> Result<(String, String), String> { let v = post(cfg, "/relay/manager/brain", &json!({"user": user, "name": "雲端大腦"}))?; let (id, token) = (v["id"].as_str().unwrap_or("").to_string(), v["token"].as_str().unwrap_or("").to_string()); if id.is_empty() || token.is_empty() { return Err(format!("帳號伺服器沒有給 {user} 的登入憑證")); } Ok((id, token)) } fn create(cfg: &Config, user: &str, d: bool, sign_in: Option<(String, String)>) -> Result<(), String> { let (id, token) = match sign_in { Some(s) => s, None => issue(cfg, user)?, }; let args = create_args(user, &id, &token, d, &layers(&cfg.image), cfg); let a: Vec<&str> = args.iter().map(String::as_str).collect(); docker(&a)?; let name = container_name(user); // Made, joined to its networks, then started — or taken away whole, to be made again. let rest = (|| { if d { if let Some(n) = &cfg.docker_network { docker(&["network", "connect", n, &name])?; } } docker(&["start", &name]) })(); if let Err(e) = rest { let _ = docker(&["rm", "-f", &name]); return Err(e); } log::info!("AnyBot 大腦管理員:{user} 的雲端大腦開好了({name}{})", if d { ",有 Bot 的電腦" } else { "" }); Ok(()) } /// The accounts, and the brain the account server knows for each (an older one doesn't say). fn accounts(cfg: &Config) -> Result<(Vec, Option>), String> { let mut r = crate::net::agent(15) .get(&format!("{}/relay/manager/users", cfg.relay)) .header("Authorization", &format!("Bearer {}", cfg.key)) .call() .map_err(|e| format!("連不到帳號伺服器({}):{e}", cfg.relay))?; let status = r.status().as_u16(); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); if status != 200 { return Err(format!("帳號伺服器不讓大腦管理員進來({status}):ANYBOT_RELAY_MANAGER_TOKEN 兩邊要一樣")); } Ok((parse_accounts(&v), parse_managed(&v))) } pub fn parse_accounts(v: &Value) -> Vec { v["users"].as_array().into_iter().flatten().filter_map(|u| u.as_str()).map(|n| Account { name: n.to_string(), created: v["created"][n].as_i64().unwrap_or(0) }).collect() } pub fn parse_managed(v: &Value) -> Option> { v["brains"].as_object().map(|m| m.iter().filter_map(|(u, id)| Some((u.clone(), id.as_str()?.to_string()))).collect()) } fn post(cfg: &Config, path: &str, body: &Value) -> Result { let mut r = crate::net::agent(15) .post(&format!("{}{path}", cfg.relay)) .header("Authorization", &format!("Bearer {}", cfg.key)) .send_json(body) .map_err(|e| format!("連不到帳號伺服器:{e}"))?; let status = r.status().as_u16(); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); if status != 200 { return Err(format!("帳號伺服器回 {status}:{}", v["error"].as_str().unwrap_or(""))); } Ok(v) } /// The brains Docker has (made by this manager: labelled with their account). fn existing() -> Result, String> { let ids = docker(&["ps", "-aq", "--filter", "label=anybot.brain.user"])?; let ids: Vec<&str> = ids.split_whitespace().collect(); if ids.is_empty() { return Ok(HashMap::new()); } let mut args = vec!["inspect", "-f", "{{index .Config.Labels \"anybot.brain.user\"}}\t{{.Name}}\t{{.State.Running}}\t{{index .Config.Labels \"anybot.brain.layers\"}}\t{{index .Config.Labels \"anybot.brain.docker\"}}\t{{index .Config.Labels \"anybot.brain.args\"}}\t{{index .Config.Labels \"anybot.brain.host\"}}\t{{range $k, $v := .NetworkSettings.Networks}}{{$k}},{{end}}"]; args.extend(ids); // (What each was made from is the label set then: a brain from before the label has none, and // is made again once.) let out = docker(&args)?; let (aside, found) = parse_inspect_aside(&out); // One made beside a brain by a remake that was cut short: never swapped in — gone. for (_, e) in parse_inspect_lines(&out).into_iter().filter(|(_, e)| e.name.ends_with("-new")) { let _ = docker(&["rm", "-f", &e.name]); } // One kept aside by a remake that was cut short (the manager stopped in the middle): put back // when there is no new one, or the new one under its name never started (not known to run — // made again instead); gone once the new one has run. let mut found = found; for (user, e) in aside { let name = container_name(&user); if let Some(now) = found.get(&user) { match aside_fate(docker(&["inspect", "-f", "{{.State.StartedAt}}", &now.name]).ok().as_deref()) { Aside::Gone => { let _ = docker(&["rm", "-f", &e.name]); continue; } Aside::Later => continue, Aside::Back => { if docker(&["rm", "-f", &now.name]).is_err() { continue; } found.remove(&user); } } } if docker(&["rename", &e.name, &name]).is_ok() { found.insert(user, Existing { name, ..e }); } } Ok(found) } /// What becomes of a brain kept aside (…-old) when one is under its name too. #[derive(Debug, PartialEq)] pub enum Aside { /// The new one has run: the remake went through, the old one goes. Gone, /// The new one never started (the manager stopped right then): not known to run — the old one /// back, made again. Back, /// Docker didn't say: both left as they are until it does. Later, } /// From when the one under its name started (`State.StartedAt`; Docker's zero time when never). pub fn aside_fate(started_at: Option<&str>) -> Aside { match started_at.map(str::trim) { None | Some("") => Aside::Later, Some(at) if at.starts_with("0001-") => Aside::Back, Some(_) => Aside::Gone, } } /// The brains and the ones kept aside (named …-old) by a remake. pub fn parse_inspect_aside(out: &str) -> (Vec<(String, Existing)>, HashMap) { let mut aside = vec![]; let mut found = HashMap::new(); for (user, e) in parse_inspect_lines(out) { if e.name.ends_with("-old") { aside.push((user, e)); } else if !e.name.ends_with("-new") { found.insert(user, e); } } (aside, found) } /// What an image holds: a hash of its layers (empty when Docker can't say). The same after a /// build that changed nothing; another when the program changed. fn layers(image: &str) -> String { match docker(&["image", "inspect", "-f", "{{range .RootFS.Layers}}{{.}},{{end}}", image]) { Ok(l) if !l.trim().is_empty() => crate::httpd::sha256_hex(l.trim())[..16].to_string(), _ => String::new(), } } pub fn parse_inspect(out: &str) -> HashMap { parse_inspect_lines(out).into_iter().collect() } fn parse_inspect_lines(out: &str) -> Vec<(String, Existing)> { out.lines() .filter_map(|l| { let f: Vec<&str> = l.split('\t').map(str::trim).collect(); let (user, name) = (*f.first()?, f.get(1)?.trim_start_matches('/')); let at = |i: usize| f.get(i).copied().unwrap_or("").trim_start_matches("").to_string(); (!user.is_empty() && !name.is_empty()).then(|| (user.to_string(), Existing { name: name.to_string(), running: f.get(2) == Some(&"true"), image: at(3), docker: f.get(4) == Some(&"1"), args: at(5), host: at(6), networks: at(7) })) }) .collect() } fn docker(args: &[&str]) -> Result { let out = Command::new("docker").args(args).output().map_err(|e| format!("執行不了 docker:{e}"))?; if out.status.success() { Ok(String::from_utf8_lossy(&out.stdout).to_string()) } else { // (The token is in `docker create`'s arguments: never in what is said.) Err(format!("docker {} 失敗:{}", args.first().unwrap_or(&""), String::from_utf8_lossy(&out.stderr).trim())) } } fn data_folder() -> std::path::PathBuf { crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir) } /// From the environment, and from the manager's own container: its image and networks. The day /// it first ran is kept in its data folder (accounts made before it are left alone). fn config() -> Result { let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); let list = |k: &str| var(k).map(|s| s.split(',').map(|x| x.trim().to_lowercase()).filter(|x| !x.is_empty()).collect()).unwrap_or_default(); let key = var("ANYBOT_RELAY_MANAGER_TOKEN").filter(|k| k.len() >= 32).ok_or("沒有 ANYBOT_RELAY_MANAGER_TOKEN(32 個字以上,跟帳號伺服器的一樣)")?; let relay = var("ANYBOT_RELAY_INTERNAL").unwrap_or_else(|| "http://relay-manager:8080".into()); let brain_relay = var("ANYBOT_BRAIN_RELAY").unwrap_or_else(|| "http://relay:8080".into()); let me = var("HOSTNAME").ok_or("不知道自己的容器(沒有 HOSTNAME)")?; let image = match var("ANYBOT_BRAIN_IMAGE") { Some(i) => i, None => docker(&["inspect", "-f", "{{.Config.Image}}", &me])?.trim().to_string(), }; let nets = docker(&["inspect", "-f", "{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}", &me])?; let nets: Vec = nets.split_whitespace().map(String::from).collect(); // The account server's network is the compose project's default one; Docker's proxy's ends // in docker-api (the manager's own network with the account server is neither). let network = nets.iter().find(|n| n.ends_with("_default")).cloned().ok_or("找不到帳號伺服器的網路")?; let docker_network = nets.iter().find(|n| n.ends_with("docker-api")).cloned(); let folder = data_folder(); let since_file = folder.join("brains-since"); let since = match std::fs::read_to_string(&since_file).ok().and_then(|s| s.trim().parse::().ok()) { Some(t) => t, None => { let t = chrono::Utc::now().timestamp(); std::fs::create_dir_all(&folder).map_err(|e| format!("寫不了資料夾:{e}"))?; std::fs::write(&since_file, t.to_string()).map_err(|e| format!("寫不了 {}:{e}", since_file.display()))?; t } }; let env = ["ANYBOT_VOICE_URL", "ANYBOT_VOICE_LISTEN_MODEL", "ANYBOT_VOICE_SPEAK_MODEL", "ANYBOT_VOICE_VOICE", "ANYBOT_HF_BASE"].iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(); let docker_env = ["DOCKER_HOST"].iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(); let memory = var("ANYBOT_BRAIN_MEMORY").filter(|m| m.chars().all(|c| c.is_ascii_alphanumeric())).unwrap_or_else(|| "4g".into()); // A share of the CPUs only where Docker can hold a container to one, and never more than the // machine has (a one-CPU server refused --cpus 2, and no brain was made). let have = std::thread::available_parallelism().map(|n| n.get() as f32).unwrap_or(1.0); let want = var("ANYBOT_BRAIN_CPUS").and_then(|m| m.parse::().ok()).filter(|n| *n > 0.0).unwrap_or(2.0); // (Not answered — the proxy still starting, an older one without INFO: asked again after a // restart, rather than every brain made again without its CPU limit and again later with.) let cfs = docker(&["info", "-f", "{{.CPUCfsQuota}}"]).map_err(|e| format!("問不到 Docker 能不能限 CPU({e})"))?.trim() == "true"; let cpus = cfs.then(|| format!("{}", want.min(have))); let max = var("ANYBOT_BRAINS_MAX").and_then(|m| m.parse::().ok()).unwrap_or(20); Ok(Config { relay, brain_relay, key, image, network, docker_network, skip: list("ANYBOT_BRAINS_SKIP"), docker_users: list("ANYBOT_BRAINS_DOCKER"), since, all: var("ANYBOT_BRAINS_ALL").as_deref() == Some("1"), memory, cpus, max, env, docker_env }) } #[cfg(test)] mod tests { use super::*; fn acct(n: &str, created: i64) -> Account { Account { name: n.into(), created } } fn cfg() -> Config { Config { relay: "http://relay-manager:8080".into(), brain_relay: "http://relay:8080".into(), key: "k".into(), image: "anybot-brain:local".into(), network: "server_default".into(), docker_network: Some("server_docker-api".into()), since: 100, memory: "4g".into(), cpus: Some("2".into()), max: 20, docker_env: vec![("DOCKER_HOST".into(), "tcp://docker-socket-proxy:2375".into())], ..Default::default() } } fn made(user: &str, docker: bool, image: &str, host: &str, c: &Config) -> Existing { Existing { name: container_name(user), running: true, image: image.into(), docker, args: args_hash(user, docker, c), host: host.into(), networks: String::new() } } /// Every account made since the manager came gets one brain: made once, started again when /// stopped, made again from a newer image or other settings, left alone while right; the /// older setup's own account and accounts from before the manager are left as they were. #[test] fn each_account_gets_one_brain() { let c = Config { skip: vec!["OLD".into()], ..cfg() }; let accounts = vec![acct("boss", 150), acct("amy", 160), acct("bob", 170), acct("old", 120), acct("family", 50), acct("new", 180), acct("set", 190)]; let mut have = HashMap::new(); have.insert("amy".to_string(), made("amy", false, "sha:1", "", &c)); have.insert("bob".to_string(), Existing { running: false, ..made("bob", false, "sha:1", "", &c) }); have.insert("new".to_string(), made("new", false, "sha:0", "", &c)); have.insert("set".to_string(), Existing { args: "made-another-way".into(), ..made("set", false, "sha:1", "", &c) }); assert_eq!( plan(&accounts, &have, "sha:1", Some("boss"), None, &c), vec![Action::Create("boss".into(), true), Action::Start(container_name("bob"), false), Action::Remake("new".into(), false, false), Action::Remake("set".into(), false, false)], "family (made before the manager) is left alone; a new brain first, the updates last" ); // At most `max` brains: four there, room for none. let full = Config { max: 4, ..c.clone() }; assert!(!plan(&accounts, &have, "sha:1", Some("boss"), None, &full).iter().any(|a| matches!(a, Action::Create(..)))); let one = Config { max: 5, ..c.clone() }; assert_eq!(plan(&accounts, &have, "sha:1", Some("boss"), None, &one).iter().filter(|a| matches!(a, Action::Create(..))).count(), 1); // A brain stopped on purpose (skipped) doesn't take a place. let stopped = Config { max: 4, skip: vec!["OLD".into(), "bob".into()], ..c.clone() }; assert_eq!(plan(&accounts, &have, "sha:1", Some("boss"), None, &stopped).iter().filter(|a| matches!(a, Action::Create(..))).count(), 1); // With every account from before too. let all = Config { all: true, ..c.clone() }; assert!(plan(&accounts, &have, "sha:1", Some("boss"), None, &all).contains(&Action::Create("family".into(), false))); // An image not known (inspect failed): no remake for it. assert!(!plan(&accounts, &have, "", Some("boss"), None, &c).iter().any(|a| matches!(a, Action::Remake(n, ..) if n == "new"))); } /// A brain whose sign-in the account server no longer has is made again with a new one; an /// older account server that doesn't say leaves it be. #[test] fn a_brain_whose_sign_in_is_gone_gets_a_new_one() { let c = cfg(); let accounts = vec![acct("boss", 150), acct("amy", 160)]; let mut have = HashMap::new(); have.insert("boss".to_string(), made("boss", true, "i", "b1", &c)); have.insert("amy".to_string(), made("amy", false, "i", "a1", &c)); let mut m = HashMap::new(); m.insert("boss".to_string(), "b1".to_string()); assert_eq!(plan(&accounts, &have, "i", Some("boss"), Some(&m), &c), vec![Action::Remake("amy".into(), false, true)]); m.insert("amy".to_string(), "a1".to_string()); assert!(plan(&accounts, &have, "i", Some("boss"), Some(&m), &c).is_empty()); assert!(plan(&accounts, &have, "i", Some("boss"), None, &c).is_empty()); } /// Docker is the whole server: only the owner's brain and the ones named; the owner is the /// first account made. #[test] fn only_the_owner_and_the_named_get_docker() { let accounts = vec![acct("amy", 200), acct("boss", 150), acct("bob", 300)]; assert_eq!(first_account(&accounts), Some("boss")); assert!(gets_docker("boss", Some("boss"), &[])); assert!(!gets_docker("amy", Some("boss"), &[]) && !gets_docker("bob", Some("boss"), &[])); assert!(gets_docker("bob", Some("boss"), &["BOB".into()])); assert!(!gets_docker("boss", None, &[])); // A brain given Docker it shouldn't have is made again without. let c = cfg(); let mut have = HashMap::new(); have.insert("amy".to_string(), made("amy", true, "i", "", &c)); have.insert("boss".to_string(), made("boss", true, "i", "", &c)); assert_eq!(plan(&accounts, &have, "i", Some("boss"), None, &c), vec![Action::Create("bob".into(), false), Action::Remake("amy".into(), false, false)]); } /// Docker names from account names: allowed letters only, apart when the names differ. #[test] fn account_names_make_docker_names() { let ok = |n: &str| n.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') && n.len() <= 60; for u in ["amy", "a.b", "a_b", "a@b.com", "Ünïcode", "-x-", "", "a-b"] { assert!(ok(&slug(u)), "{u} → {}", slug(u)); assert!(ok(&format!("anybot-box-home-{}", slug(u)))); } assert_ne!(slug("a.b"), slug("a_b")); assert_ne!(slug("a@b"), slug("a-b")); assert_eq!(slug("amy"), slug("amy")); assert!(container_name("amy").starts_with("anybot-brain-amy-")); } /// A brain's `docker create`: its account, sign-in, own volume, the account server's network, /// no raw packets or new privileges, its limits; Docker, its box and the box's home only for a /// brain given Docker; how it was made and its sign-in's id as labels; the image and /// `anybot --serve` last; no password. #[test] fn a_brain_runs_with_its_own_things() { let s = slug("amy"); let has = |a: &[String], pair: [&str; 2]| a.windows(2).any(|w| w[0] == pair[0] && w[1] == pair[1]); let with = create_args("amy", "id1", "tok1", true, "abc123", &cfg()); assert_eq!(with[0], "create"); assert!(has(&with, ["--restart", "unless-stopped"]) && has(&with, ["--name", &container_name("amy")])); assert!(has(&with, ["-v", &format!("anybot-brain-{s}:/data")]) && has(&with, ["--network", "server_default"])); assert!(has(&with, ["--cap-drop", "NET_RAW"]) && has(&with, ["--security-opt", "no-new-privileges"]) && has(&with, ["--memory", "4g"]) && has(&with, ["--memory-swap", "4g"]) && has(&with, ["--cpus", "2"]) && has(&with, ["--pids-limit", "2048"])); assert!(has(&with, ["--label", "anybot.brain.user=amy"]) && has(&with, ["--label", "anybot.brain.docker=1"]) && has(&with, ["--label", "anybot.brain.host=id1"])); assert!(has(&with, ["--label", &format!("anybot.brain.args={}", args_hash("amy", true, &cfg()))]) && has(&with, ["--label", "anybot.brain.layers=abc123"])); for e in ["ANYBOT_ACCOUNT=http://relay:8080|amy", "ANYBOT_HOST_ID=id1", "ANYBOT_HOST_TOKEN=tok1", &format!("ANYBOT_BOX_NAME=anybot-box-{s}"), &format!("ANYBOT_BOX_VOLUME=anybot-box-home-{s}"), "DOCKER_HOST=tcp://docker-socket-proxy:2375"] { assert!(has(&with, ["-e", e]), "{e} in {with:?}"); } assert_eq!(&with[with.len() - 3..], ["anybot-brain:local", "anybot", "--serve"]); assert!(!with.iter().any(|x| x.contains("PASSWORD") || x.contains("relay-manager")), "no password; the manager's own way to the account server isn't the brain's"); // A Docker that can't hold a container to a share of the CPUs: no --cpus (it was refused). assert!(!create_args("amy", "id1", "tok1", true, "abc123", &Config { cpus: None, ..cfg() }).iter().any(|x| x == "--cpus")); // Without Docker: no proxy, no box; the network is the account server's only. let without = create_args("amy", "id1", "tok1", false, "abc123", &cfg()); assert!(!without.iter().any(|x| x.contains("DOCKER_HOST") || x.contains("ANYBOT_BOX") || x.contains("docker-api")), "{without:?}"); assert!(has(&without, ["--label", "anybot.brain.docker=0"]) && has(&without, ["--cap-drop", "NET_RAW"])); // The sign-in isn't part of how it was made: a new one doesn't make it "different". assert_eq!(args_hash("amy", true, &cfg()), args_hash("amy", true, &cfg())); assert_ne!(args_hash("amy", true, &cfg()), args_hash("amy", false, &cfg())); assert_ne!(args_hash("amy", true, &cfg()), args_hash("amy", true, &Config { memory: "8g".into(), ..cfg() })); } /// A brain kept aside by a remake (…-old) is told apart from the brains. #[test] fn a_brain_kept_aside_is_told_apart() { let (aside, found) = parse_inspect_aside("amy\t/anybot-brain-amy-1-old\tfalse\tl1\t1\th\tid\nbob\t/anybot-brain-bob-2\ttrue\tl1\t0\th\tid\nbob\t/anybot-brain-bob-2-new\tfalse\tl2\t0\th\tid\n"); assert_eq!(aside.len(), 1); assert_eq!(found["bob"].name, "anybot-brain-bob-2", "one made beside it isn't the brain"); assert_eq!(aside[0].0, "amy"); assert!(found.contains_key("bob") && !found.contains_key("amy")); } /// The networks a brain is on are read back, and its way to Docker told apart. #[test] fn a_brains_networks_are_read_back() { let found = super::parse_inspect("amy\t/anybot-brain-amy-1\ttrue\tl1\t1\th\tid\tserver_default,server_docker-api,\nbob\t/anybot-brain-bob-2\ttrue\tl1\t0\th\tid\tserver_default,\n"); assert!(super::on_network(&found["amy"], "server_docker-api")); assert!(!super::on_network(&found["bob"], "server_docker-api")); assert!(!super::on_network(&found["bob"], "server_docker"), "a name that only starts the same isn't it"); } /// A brain kept aside goes once the new one has run, and comes back when it never started. #[test] fn a_brain_kept_aside_comes_back_unless_the_new_one_ran() { use super::{aside_fate, Aside}; assert_eq!(aside_fate(Some("2026-11-23T00:37:28.385270556Z\n")), Aside::Gone); assert_eq!(aside_fate(Some("0001-01-01T00:00:00Z\n")), Aside::Back); assert_eq!(aside_fate(None), Aside::Later, "Docker didn't answer"); assert_eq!(aside_fate(Some("")), Aside::Later); } /// An account that keeps failing is tried less and less often, never less than every half hour. #[test] fn an_account_that_keeps_failing_rests_longer() { let mins: Vec = (1..=8).map(|n| super::rest_for(n).as_secs() / 60).collect(); assert_eq!(mins, [1, 2, 4, 8, 16, 30, 30, 30]); assert_eq!(super::rest_for(0).as_secs(), 60); } #[test] fn what_docker_and_the_account_server_say_reads_back() { let m = parse_inspect("amy\t/anybot-brain-amy-1\ttrue\tsha256:aa\t1\th1\tid9\nbob\t/anybot-brain-bob-2\tfalse\tsha256:bb\t0\t\t\n\n\tx\ty\n"); assert_eq!(m.len(), 2); assert!(m["amy"].running && m["amy"].docker && !m["bob"].running && !m["bob"].docker); assert_eq!((m["amy"].args.as_str(), m["amy"].host.as_str()), ("h1", "id9")); assert_eq!((m["bob"].name.as_str(), m["bob"].image.as_str(), m["bob"].args.as_str(), m["bob"].host.as_str()), ("anybot-brain-bob-2", "sha256:bb", "", "")); let v = json!({"users": ["boss", "amy"], "created": {"boss": 10, "amy": 20}, "brains": {"amy": "a1"}}); assert_eq!(parse_accounts(&v), vec![acct("boss", 10), acct("amy", 20)]); assert_eq!(parse_managed(&v).unwrap().get("amy").map(String::as_str), Some("a1")); // An older account server without the times or the brains. assert_eq!(parse_accounts(&json!({"users": ["x"]})), vec![acct("x", 0)]); assert!(parse_managed(&json!({"users": ["x"]})).is_none()); } }