agentmux_srv/server/app_api/
container_limits.rs1use axum::extract::State;
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Response};
15use axum::{Extension, Json};
16use serde::Deserialize;
17use serde_json::{json, Value};
18
19use crate::backend::container::limits::{normalize, ContainerLimits, Target};
20use crate::backend::rpc_types::AgentContainerLimitsResult;
21use crate::server::caller::Caller;
22use crate::server::state::AppState;
23
24pub(crate) type Refusal = (StatusCode, String);
26
27fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
28 (status, message.into())
29}
30
31pub(crate) fn container_agent(state: &AppState, named: &str) -> Result<(String, crate::backend::storage::AgentDefinition), Refusal> {
33 let named = named.trim();
34 let uid = crate::backend::agent_resolve::resolve_agent_id(&state.mstore, named)
35 .map_err(|_| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine")))?;
36 let def = state
37 .mstore
38 .agent_def_get(&uid)
39 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?
40 .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine")))?;
41 if !def.runtime().is_container() {
42 return Err(refuse(StatusCode::CONFLICT, format!("{} does not run in a container, so it has no container limits", def.name)));
43 }
44 Ok((uid, def))
45}
46
47fn mb_of(bytes: i64) -> u64 {
48 bytes as u64 / (1024 * 1024)
49}
50
51pub(crate) async fn view(state: &AppState, uid: &str, applied: Option<bool>) -> Result<AgentContainerLimitsResult, Refusal> {
53 let (memory_mb, cpus) = state
54 .mstore
55 .container_limits_get(uid)
56 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?
57 .unwrap_or_default();
58 let mut out = AgentContainerLimitsResult {
59 memory_mb: memory_mb.clone(),
60 cpus: cpus.clone(),
61 effective_memory_mb: None,
62 effective_cpus: None,
63 daemon_memory_mb: None,
64 daemon_cpus: None,
65 applied,
66 };
67 if let Some(cm) = state.container_manager.get().await {
68 let name = crate::backend::container::container_name_for_slug(uid);
69 let wanted = cm.wanted_limits_for_container(&name, ContainerLimits::from_strings(&memory_mb, &cpus)).await;
70 if let Target::Set(bytes) = wanted.memory {
71 out.effective_memory_mb = Some(mb_of(bytes));
72 }
73 if let Target::Set(nano) = wanted.cpus {
74 out.effective_cpus = Some(nano as f64 / 1e9);
75 }
76 if let Some(capacity) = cm.daemon_capacity().await {
77 out.daemon_memory_mb = Some(capacity.mem_total / (1024 * 1024));
78 out.daemon_cpus = Some(capacity.ncpu);
79 }
80 }
81 Ok(out)
82}
83
84pub(crate) async fn set(
87 state: &AppState,
88 uid: &str,
89 def: &crate::backend::storage::AgentDefinition,
90 memory: Option<&Value>,
91 cpus: Option<&Value>,
92 by: &str,
93) -> Result<AgentContainerLimitsResult, Refusal> {
94 let memory = memory.map(|v| normalize(v, "memory_mb")).transpose().map_err(|m| refuse(StatusCode::BAD_REQUEST, m))?;
95 let cpus = cpus.map(|v| normalize(v, "cpus")).transpose().map_err(|m| refuse(StatusCode::BAD_REQUEST, m))?;
96 let (old_memory, old_cpus) = state.mstore.container_limits_get(uid).ok().flatten().unwrap_or_default();
97 let (memory, cpus) = (memory.unwrap_or(old_memory), cpus.unwrap_or(old_cpus));
98 state
99 .mstore
100 .container_limits_set(uid, &memory, &cpus)
101 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?;
102
103 let mut applied = None;
105 if let Some(cm) = state.container_manager.get().await {
106 let name = crate::backend::container::container_name_for_slug(uid);
107 applied = cm.limits_apply(&name, ContainerLimits::from_strings(&memory, &cpus)).await;
108 }
109 let result = view(state, uid, applied).await?;
110 tracing::info!(agent = %def.slug, %by, memory_mb = %memory, cpus = %cpus, ?applied, "container limits set");
111 note_in_pane(state, uid, def, &result, by);
112 Ok(result)
113}
114
115fn note_in_pane(state: &AppState, uid: &str, def: &crate::backend::storage::AgentDefinition, result: &AgentContainerLimitsResult, by: &str) {
117 let Some(registration) = crate::backend::reactive::handler::get_global_handler().get_agent(&def.slug) else { return };
118 let block_id = registration.block_id;
119 let provider = match state.mstore.get::<crate::backend::obj::Block>(&block_id) {
120 Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "claude"),
121 _ => return,
122 };
123 let (state_name, error) = match result.applied {
124 Some(false) => ("failed", Some("Docker did not take the new limits; the container keeps the ones it has")),
125 _ => ("changed", None),
126 };
127 let frame = crate::backend::cli_notice::container_limit_frame(
128 &provider,
129 &block_id,
130 (uid, &def.name),
131 state_name,
132 result.effective_memory_mb,
133 result.effective_cpus,
134 Some(by),
135 error,
136 );
137 crate::backend::cli_notice::append_to_pane(&state.broker, &state.filestore, &state.mstore, &block_id, &frame);
138}
139
140#[derive(Debug, Deserialize)]
143pub(crate) struct LimitsRequest {
144 agent: String,
145 #[serde(default)]
147 memory_mb: Option<Value>,
148 #[serde(default)]
150 cpus: Option<Value>,
151}
152
153async fn run(state: &AppState, caller: Option<&Caller>, req: LimitsRequest) -> Result<Value, Refusal> {
154 let (uid, def) = container_agent(state, &req.agent)?;
155 let changing = req.memory_mb.is_some() || req.cpus.is_some();
156 let mut by = "you".to_string();
157 if let Some(caller_uid) = caller.and_then(Caller::uid) {
158 let caller_def = state
159 .mstore
160 .agent_def_get(caller_uid)
161 .ok()
162 .flatten()
163 .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
164 if changing && caller_def.runtime().is_container() {
165 return Err(refuse(
166 StatusCode::FORBIDDEN,
167 "CONTAINER_AGENT: a container agent cannot change a container's limits, its own included. Ask a host agent, \
168 your steward or the operator to raise it, saying how much memory the work needs and why",
169 ));
170 }
171 by = caller_def.name;
172 }
173 let result = if changing {
174 set(state, &uid, &def, req.memory_mb.as_ref(), req.cpus.as_ref(), &by).await?
175 } else {
176 view(state, &uid, None).await?
177 };
178 Ok(json!({
179 "agent": def.name,
180 "limits": result,
181 "note": "memory_mb and cpus are what is set (empty: auto, \"0\": no limit); effective_* is what is in force now, \
182 and daemon_* what Docker has in total. A change is put on the running container at once",
183 }))
184}
185
186pub(crate) async fn handle_container_limits(
187 State(state): State<AppState>,
188 caller: Option<Extension<Caller>>,
189 Json(req): Json<LimitsRequest>,
190) -> Response {
191 let caller = caller.map(|Extension(c)| c);
192 match run(&state, caller.as_ref(), req).await {
193 Ok(body) => Json(body).into_response(),
194 Err((status, message)) => (status, Json(json!({ "error": message }))).into_response(),
195 }
196}