-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreconciliation.rs
More file actions
433 lines (386 loc) · 14 KB
/
reconciliation.rs
File metadata and controls
433 lines (386 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Server-startup reconciliation: sync SQLite state with live Docker state.
//!
//! Called once during [`run_server`] startup, before accepting connections.
//!
//! ## What it does
//!
//! 1. **Dead sessions** — sessions with state `Starting` or `Running` in DB
//! whose container no longer exists (or has exited) are marked `Stopped`.
//!
//! 2. **Orphan containers** — containers labelled `relay.managed=true` that
//! have no corresponding DB session are force-removed.
//!
//! 3. **Orphan networks** — Docker networks labelled `relay.managed=true`
//! that are not attached to any managed container are removed.
//!
//! All errors during reconciliation are logged and tolerated — a partial
//! reconciliation is better than refusing to start.
use std::collections::HashSet;
use tracing::{error, info, warn};
use crate::docker::DockerOrchestrator;
use crate::store::Store;
// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------
/// Run the full reconciliation pass.
///
/// Errors from individual reconciliation steps are logged but not propagated;
/// the server should start even if cleanup is partial.
pub async fn reconcile(store: &Store, docker: &DockerOrchestrator) {
info!("reconciliation: starting");
// Fetch the container list once and share it between steps 1 and 2, which
// can run in parallel. Step 3 re-fetches after step 2 has removed orphan
// containers so the network check sees the updated state.
let containers = match docker.list_managed_containers().await {
Ok(c) => c,
Err(e) => {
error!(error = %e, "reconciliation: failed to list Docker containers");
info!(
dead_sessions = 0,
orphan_containers = 0,
orphan_networks = 0,
"reconciliation: complete (skipped — Docker unavailable)"
);
return;
}
};
let (dead_sessions, orphan_containers) = tokio::join!(
reconcile_dead_sessions(store, &containers),
reconcile_orphan_containers(store, docker, &containers),
);
let orphan_networks = reconcile_orphan_networks(docker).await;
info!(
dead_sessions,
orphan_containers, orphan_networks, "reconciliation: complete"
);
}
// ---------------------------------------------------------------------------
// Step 1 — mark dead sessions as Stopped
// ---------------------------------------------------------------------------
/// Mark `Starting`/`Running` sessions whose container is absent or not running
/// as `Stopped`.
///
/// Returns the number of sessions updated.
async fn reconcile_dead_sessions(
store: &Store,
containers: &[bollard::models::ContainerSummary],
) -> u32 {
// Collect the set of container IDs that are currently running in Docker.
let running_ids: HashSet<String> = containers
.iter()
.filter_map(|c| {
// Only containers in a "running" state count as alive.
let is_running = matches!(
c.state,
Some(bollard::models::ContainerSummaryStateEnum::RUNNING)
);
if is_running {
c.id.clone()
} else {
None
}
})
.collect();
let active_sessions = match store.list_active_sessions().await {
Ok(s) => s,
Err(e) => {
error!(error = %e, "reconciliation: failed to list active sessions from DB");
return 0;
}
};
let mut stopped = 0u32;
for session in active_sessions {
let container_alive = session
.container_id
.as_deref()
.is_some_and(|cid| running_ids.contains(cid));
if !container_alive {
let container_id = session.container_id.as_deref().unwrap_or("<none>");
match store
.force_stop_session(&session.id, "container not found after runner restart")
.await
{
Ok(true) => {
info!(
session_id = %session.id,
container_id,
"reconciliation: session marked Stopped (container dead)"
);
stopped += 1;
}
Ok(false) => {
// Already stopped by a concurrent writer — nothing to do.
}
Err(e) => {
warn!(
session_id = %session.id,
error = %e,
"reconciliation: failed to stop dead session"
);
}
}
}
}
stopped
}
// ---------------------------------------------------------------------------
// Step 2 — remove orphan containers
// ---------------------------------------------------------------------------
/// Remove managed containers that have no corresponding DB session.
///
/// Returns the number of containers removed.
async fn reconcile_orphan_containers(
store: &Store,
docker: &DockerOrchestrator,
containers: &[bollard::models::ContainerSummary],
) -> u32 {
let mut removed = 0u32;
for container in containers {
let container_id = match &container.id {
Some(id) => id.clone(),
None => continue,
};
// Extract the session ID from the container's labels.
let session_id = container
.labels
.as_ref()
.and_then(|l| l.get("relay.session_id"))
.cloned();
let is_orphan = match &session_id {
None => {
// No session label at all — treat as orphan.
true
}
Some(sid) => match store.get_session(sid).await {
Ok(Some(_)) => false, // Session exists in DB — keep container.
Ok(None) => true, // No DB record — orphan.
Err(e) => {
warn!(
container_id = %container_id,
session_id = %sid,
error = %e,
"reconciliation: DB lookup failed, skipping container"
);
false // Skip on error to avoid false-positive removal.
}
},
};
if is_orphan {
match docker.remove_container(&container_id).await {
Ok(()) => {
info!(
container_id = %container_id,
session_id = ?session_id,
"reconciliation: orphan container removed"
);
removed += 1;
}
Err(e) => {
warn!(
container_id = %container_id,
error = %e,
"reconciliation: failed to remove orphan container"
);
}
}
}
}
removed
}
// ---------------------------------------------------------------------------
// Step 3 — remove orphan networks
// ---------------------------------------------------------------------------
/// Remove managed networks that are not connected to any managed container.
///
/// Returns the number of networks removed.
async fn reconcile_orphan_networks(docker: &DockerOrchestrator) -> u32 {
// Re-fetch containers (after orphan container removal) to get the live set.
let containers = match docker.list_managed_containers().await {
Ok(c) => c,
Err(e) => {
error!(error = %e, "reconciliation: failed to list containers for network check");
return 0;
}
};
// Build the set of network names that still have at least one container.
let occupied_networks: HashSet<String> = containers
.into_iter()
.filter_map(|c| c.network_settings)
.filter_map(|ns| ns.networks)
.flat_map(std::collections::HashMap::into_keys)
.collect();
let networks = match docker.list_managed_networks().await {
Ok(n) => n,
Err(e) => {
error!(error = %e, "reconciliation: failed to list managed networks");
return 0;
}
};
let mut removed = 0u32;
for network in networks {
let name = match &network.name {
Some(n) => n.clone(),
None => continue,
};
if !occupied_networks.contains(&name) {
match docker.remove_network_if_exists(&name).await {
Ok(()) => {
info!(network = %name, "reconciliation: orphan network removed");
removed += 1;
}
Err(e) => {
warn!(
network = %name,
error = %e,
"reconciliation: failed to remove orphan network"
);
}
}
}
}
removed
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::store::{CreateProject, CreateSession, SessionState, Store};
async fn make_store() -> Store {
Store::for_tests().await
}
#[tokio::test]
async fn list_active_sessions_returns_starting_and_running() {
let store = make_store().await;
// Create project → workspace → 3 sessions in different states.
let proj = store
.create_project(CreateProject {
name: "p".into(),
git_url: "https://example.com/repo.git".into(),
local_path: "/tmp/p".into(),
})
.await
.expect("create project");
// Session 1: Starting (default after create_session)
let s1 = store
.create_session(CreateSession {
project_id: proj.id.clone(),
branch: "main".into(),
image: "ubuntu:24.04".into(),
profile: "default".into(),
work_dir: String::new(),
})
.await
.expect("create session s1");
// Session 2: Running
let s2 = store
.create_session(CreateSession {
project_id: proj.id.clone(),
branch: "main".into(),
image: "ubuntu:24.04".into(),
profile: "default".into(),
work_dir: String::new(),
})
.await
.expect("create session s2");
store
.update_session_state(
&s2.id,
SessionState::Running,
Some("cid-running"),
None,
&s2.updated_at.to_rfc3339(),
)
.await
.expect("update s2 to Running");
// Session 3: Stopped
let s3 = store
.create_session(CreateSession {
project_id: proj.id.clone(),
branch: "main".into(),
image: "ubuntu:24.04".into(),
profile: "default".into(),
work_dir: String::new(),
})
.await
.expect("create session s3");
store
.update_session_state(
&s3.id,
SessionState::Stopped,
None,
None,
&s3.updated_at.to_rfc3339(),
)
.await
.expect("update s3 to Stopped");
let active = store
.list_active_sessions()
.await
.expect("list active sessions");
let ids: Vec<&str> = active.iter().map(|s| s.id.as_str()).collect();
assert!(
ids.contains(&s1.id.as_str()),
"Starting session should be active"
);
assert!(
ids.contains(&s2.id.as_str()),
"Running session should be active"
);
assert!(
!ids.contains(&s3.id.as_str()),
"Stopped session should not be active"
);
}
#[tokio::test]
async fn force_stop_session_updates_state() {
let store = make_store().await;
let proj = store
.create_project(CreateProject {
name: "p2".into(),
git_url: "https://example.com/repo.git".into(),
local_path: "/tmp/p2".into(),
})
.await
.expect("create project");
let session = store
.create_session(CreateSession {
project_id: proj.id.clone(),
branch: "main".into(),
image: "ubuntu:24.04".into(),
profile: "default".into(),
work_dir: String::new(),
})
.await
.expect("create session");
// First call should succeed (state is Starting).
let updated = store
.force_stop_session(&session.id, "container not found after runner restart")
.await
.expect("force_stop_session first call");
assert!(
updated,
"force_stop_session should return true when updating Starting"
);
// Verify state is now Stopped.
let fetched = store
.get_session(&session.id)
.await
.expect("get_session query")
.expect("session should exist");
assert_eq!(fetched.state, SessionState::Stopped);
assert_eq!(
fetched.error_reason.as_deref(),
Some("container not found after runner restart")
);
// Second call on already-stopped session should return false.
let updated_again = store
.force_stop_session(&session.id, "should not change")
.await
.expect("force_stop_session second call");
assert!(
!updated_again,
"force_stop_session should return false when already Stopped"
);
}
}