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
use crate::entities::containers;
use crate::query::Query;
use crate::state::AppState;
use std::sync::Arc;
use tokio::task::JoinHandle;
use tracing::{debug, error, info};
use anyhow::Result;
use dashmap::DashMap;
use once_cell::sync::Lazy;
use sea_orm::ActiveModelTrait;
use serde::{Deserialize, Serialize};
use short_uuid::ShortUuid;
/// A struct defining any reconciler metadata you want to store in `controller_data`.
/// This might hold more fields (timestamps, logs, etc.) if desired.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ReconcilerData {
thread_id: Option<String>,
}
/// A global map from some container "thread_id" -> the running JoinHandle.
/// We’ll store the `thread_id` in DB and look it up here to see if it’s finished.
static CONTAINER_RECON_TASKS: Lazy<DashMap<String, JoinHandle<()>>> = Lazy::new(DashMap::new);
pub struct ContainerController {
app_state: Arc<AppState>,
}
impl ContainerController {
pub fn new(app_state: Arc<AppState>) -> Self {
Self { app_state }
}
/// The main loop that spawns or skips reconciliation tasks (threads).
/// Each container’s `controller_data` field will hold the JSON specifying its `thread_id`.
pub async fn reconcile(&self) {
info!("[Container Controller] Starting container reconciliation process");
match Query::find_all_active_containers(&self.app_state.db_pool).await {
Ok(containers) => {
debug!(
"[DEBUG:controller.rs:reconcile] Found {} containers to reconcile",
containers.len()
);
for container in containers {
debug!(
"[DEBUG:controller.rs:reconcile] Inspecting container {}",
container.id
);
// Attempt to parse `controller_data` as `ReconcilerData`.
let mut existing_data =
match container.parse_controller_data::<ReconcilerData>() {
Ok(Some(data)) => data,
_ => ReconcilerData { thread_id: None },
};
debug!(
"[DEBUG:controller.rs:reconcile] Existing thread_id = {:?}",
existing_data.thread_id,
);
// If there's already a thread_id, check if it's still alive.
if let Some(thread_id) = &existing_data.thread_id {
if let Some(handle_ref) = CONTAINER_RECON_TASKS.get(thread_id) {
// If handle still running, skip starting a new one.
debug!(
"[DEBUG:controller.rs:reconcile] handle_ref.is_finished() = {}",
handle_ref.is_finished()
);
if !handle_ref.is_finished() {
info!(
"[Container Controller] Container {} has a running reconcile thread; skipping.",
container.id
);
continue;
} else {
debug!(
"[DEBUG:controller.rs] handle_ref.is_finished() = false; dropping ref",
);
// Drop the read reference to avoid deadlock
drop(handle_ref);
debug!(
"[DEBUG:controller.rs] Removing finished thread_id = {} from map",
thread_id
);
// Now remove from the map
let removed = CONTAINER_RECON_TASKS.remove(thread_id);
debug!("[DEBUG:controller.rs] remove(...) returned: {:?}", removed);
}
}
}
debug!(
"[DEBUG:controller.rs:reconcile] Spawning a new reconcile task for container {}",
container.id
);
// Otherwise, we spawn a fresh task.
let new_thread_id = ShortUuid::generate().to_string();
existing_data.thread_id = Some(new_thread_id.clone());
// Persist new `thread_id` in `controller_data`, so if we lose the process,
// we at least know which container was last assigned which thread ID.
if let Err(e) = Self::store_thread_id_in_db(
&container,
&existing_data,
&self.app_state.db_pool,
)
.await
{
error!(
"[Container Controller] Failed to store new thread_id for container {}: {:?}",
container.id, e
);
continue;
}
// Actually spawn a background task
let handle = tokio::spawn({
let db_pool = self.app_state.db_pool.clone();
let container_clone = container.clone();
async move {
info!(
"[Container Controller] Reconciling container {} in background task",
container_clone.id
);
debug!(
"[DEBUG:controller.rs:spawn] Calling platform.reconcile for container {}",
container_clone.id
);
// If your platform_factory is async, call it here.
let platform_name = container_clone
.platform
.clone()
.unwrap_or_else(|| "runpod".to_string());
let platform =
crate::resources::v1::containers::factory::platform_factory(
platform_name,
);
let _ = platform.reconcile(&container_clone, &db_pool).await;
debug!(
"[DEBUG:controller.rs:spawn] Returned from platform.reconcile for container {}",
container_clone.id
);
info!(
"[Container Controller] Container {} reconcile task finished.",
container_clone.id
)
}
});
// Store handle in the map
CONTAINER_RECON_TASKS.insert(new_thread_id, handle);
}
}
Err(e) => {
error!(
"[Container Controller] Failed to fetch containers for reconciliation: {:?}",
e
);
}
}
debug!("[DEBUG:controller.rs:reconcile] Finished single reconcile pass");
}
/// Helper to save the updated `controller_data` back into the DB.
async fn store_thread_id_in_db(
container: &containers::Model,
rec_data: &ReconcilerData,
db_pool: &sea_orm::DatabaseConnection,
) -> Result<(), sea_orm::DbErr> {
// Convert to JSON
let data_json = serde_json::to_value(rec_data).unwrap_or_default();
// Build an ActiveModel for the update
let mut active = containers::ActiveModel::from(container.clone());
active.controller_data = sea_orm::ActiveValue::Set(Some(data_json));
// Perform the update
active.update(db_pool).await?;
Ok(())
}
}
impl ContainerController {
/// Spawns a background Tokio task to run the controller reconciliation loop
pub fn spawn_reconciler(&self) -> tokio::task::JoinHandle<()> {
let app_state_clone = Arc::clone(&self.app_state);
tokio::spawn(async move {
let controller = ContainerController::new(app_state_clone);
// Create an infinite loop to continuously reconcile containers
loop {
controller.reconcile().await;
// Add a delay between reconciliation cycles
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
}
})
}
}