rustploy 0.1.25

Rustploy PaaS daemon — lightweight self-hosted deployment platform
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
//! Docker-wide inventory for the Docker tab: every image/volume/network on
//! the host (not just rustploy-managed resources), plus a robust "stop
//! everything rustploy manages" command.

use crate::bootstrap::state::AppState;
use shared::{
    DockerContainerInfo, DockerImageInfo, DockerNetworkInfo, DockerVolumeInfo,
    Response as RpResponse, ServiceSource, ServiceStatus,
};
use std::collections::HashMap;

/// Best-effort project/service ownership lookup, built once per request from
/// the current DB state. Two ways a Docker resource points back to a service:
/// - Git-built images/containers are tagged `rp_<safe_name>:...` (see
///   `deploy/executor.rs`'s `BuildingImage` step) — matched by `safe_name`.
/// - Registry-sourced services reference the image string verbatim.
/// - Project networks are matched by the name stored in
///   `project.network_name` (`db::projects::network_names`).
struct ServiceIndex {
    by_safe_name: HashMap<String, (String, String)>,
    by_registry_image: HashMap<String, (String, String)>,
    /// nome da rede Docker (gravado em `project.network_name`) → nome do projeto.
    by_network: HashMap<String, String>,
    /// service_id → (nome do projeto, nome do serviço), para atribuir um
    /// container pelo label `rustploy.service_id` (exato). Ver `list_containers`.
    by_service_id: HashMap<String, (String, String)>,
}

/// Serviços que **sumiram do estado por um commit externo** (marca `state_git_removed`), para
/// apontar os containers que ficaram órfãos. Um serviço normal é reconhecido pelo label
/// `rustploy.service_id`; um Compose (os bancos do assistente, por exemplo) só pelo nome da stack
/// (`com.docker.compose.project`), por isso a marca guarda os dois.
#[derive(Default)]
struct OrphanIndex {
    /// id do serviço → nome.
    by_service_id: HashMap<String, String>,
    /// nome da stack Compose → nome do serviço.
    by_compose_project: HashMap<String, String>,
}

impl OrphanIndex {
    async fn build(state: &AppState) -> Self {
        let mut o = Self::default();
        for r in crate::store::state_git_marks::list_removed(&state.db)
            .await
            .unwrap_or_default()
        {
            if let Some(id) = r.id.strip_prefix("serviço:") {
                o.by_service_id.insert(id.to_string(), r.name.clone());
                if let Some(cp) = r.compose_project {
                    o.by_compose_project.insert(cp, r.name);
                }
            }
        }
        o
    }

    fn lookup(&self, labels: &HashMap<String, String>) -> Option<String> {
        if let Some(sid) = labels.get("rustploy.service_id")
            && let Some((_, name)) = self
                .by_service_id
                .iter()
                .find(|(id, _)| crate::engine::containers::label_owned_by(sid, id))
        {
            return Some(name.clone());
        }
        // O Rustploy usa o `docker-compose` nos dois engines (no Podman também, falando com o socket
        // do Podman), então o rótulo da stack é sempre este.
        labels
            .get("com.docker.compose.project")
            .and_then(|cp| self.by_compose_project.get(cp))
            .cloned()
    }
}

impl ServiceIndex {
    async fn build(state: &AppState) -> Self {
        let projects = crate::store::projects::list(&state.db)
            .await
            .unwrap_or_default();
        let project_names: HashMap<String, String> = projects
            .iter()
            .map(|p| (p.id.clone(), p.name.clone()))
            .collect();
        let network_of = crate::store::projects::network_names(&state.db)
            .await
            .unwrap_or_default();
        let by_network = projects
            .iter()
            .filter_map(|p| Some((network_of.get(&p.id)?.clone(), p.name.clone())))
            .collect();

        let services = crate::store::services::list_all(&state.db)
            .await
            .unwrap_or_default();
        let mut by_safe_name = HashMap::new();
        let mut by_registry_image = HashMap::new();
        let mut by_service_id = HashMap::new();
        for s in &services {
            let project_name = project_names
                .get(&s.spec.project_id)
                .cloned()
                .unwrap_or_else(|| s.spec.project_id.clone());
            by_service_id.insert(s.id.clone(), (project_name.clone(), s.spec.name.clone()));
            match &s.spec.source {
                ServiceSource::Git(_) | ServiceSource::Archive(_) => {
                    by_safe_name.insert(s.spec.safe_name(), (project_name, s.spec.name.clone()));
                }
                ServiceSource::Registry { image } => {
                    by_registry_image.insert(image.clone(), (project_name, s.spec.name.clone()));
                }
                ServiceSource::Compose(_) => {}
            }
        }
        Self {
            by_safe_name,
            by_registry_image,
            by_network,
            by_service_id,
        }
    }

    /// Resolves an image's owner from its tags: exact match for registry
    /// images, `rp_<safe_name>:...` prefix match for Git-built ones.
    fn image_owner(&self, tags: &[String]) -> (Option<String>, Option<String>) {
        for tag in tags {
            if let Some((proj, svc)) = self.by_registry_image.get(tag) {
                return (Some(proj.clone()), Some(svc.clone()));
            }
            if let Some(safe) = tag
                .split(':')
                .next()
                .and_then(|repo| repo.strip_prefix("rp_"))
                && let Some((proj, svc)) = self.by_safe_name.get(safe)
            {
                return (Some(proj.clone()), Some(svc.clone()));
            }
        }
        (None, None)
    }

    /// Resolves a network's owning project from the stored network name.
    /// `None` for non-rustploy networks.
    fn network_project(&self, name: &str) -> Option<String> {
        self.by_network.get(name).cloned()
    }
}

/// Lists every image on the host via `docker system df`, the one Docker
/// Engine endpoint that always computes `Containers` (in-use count) — the
/// plain image-list endpoint leaves it `-1` unless separately requested.
/// Served from the TTL cache (`state.docker_cache.df`) so the 2s status poll
/// doesn't re-run `docker system df` every tick.
pub async fn list_images(state: AppState) -> RpResponse {
    match state
        .docker_cache
        .df
        .get_or_refresh(|| compute_df_inventory(&state))
        .await
    {
        Ok((images, _)) => RpResponse::DockerImages(images),
        Err(e) => RpResponse::err("RuntimeError", e),
    }
}

/// Lists every volume on the host via `docker system df`, which (unlike the
/// plain volume-list endpoint) populates `UsageData` — the reference count
/// that determines whether a volume is "in use". Shares the cached `df` snapshot
/// with [`list_images`].
pub async fn list_volumes(state: AppState) -> RpResponse {
    match state
        .docker_cache
        .df
        .get_or_refresh(|| compute_df_inventory(&state))
        .await
    {
        Ok((_, volumes)) => RpResponse::DockerVolumes(volumes),
        Err(e) => RpResponse::err("RuntimeError", e),
    }
}

/// Runs `docker system df` once and turns it into both the image and volume
/// inventories (ownership attributed from the current DB state). The cache
/// miss-path of [`list_images`]/[`list_volumes`].
async fn compute_df_inventory(
    state: &AppState,
) -> Result<(Vec<DockerImageInfo>, Vec<DockerVolumeInfo>), String> {
    let df = state.docker.inner.df().await.map_err(|e| e.to_string())?;
    let idx = ServiceIndex::build(state).await;
    // O `df` do Podman devolve UMA entrada por tag da mesma imagem (mesmo `id`
    // repetido); a lista e a remoção trabalham por imagem, então funde-as.
    let mut images: Vec<bollard::models::ImageSummary> = Vec::new();
    for img in df.images.unwrap_or_default() {
        match images.iter_mut().find(|seen| seen.id == img.id) {
            Some(seen) => {
                for tag in img.repo_tags {
                    if !seen.repo_tags.contains(&tag) {
                        seen.repo_tags.push(tag);
                    }
                }
                seen.containers = seen.containers.max(img.containers);
            }
            None => images.push(img),
        }
    }
    let images: Vec<DockerImageInfo> = images
        .into_iter()
        .map(|img| {
            let (project, service) = idx.image_owner(&img.repo_tags);
            DockerImageInfo {
                id: img.id,
                tags: img.repo_tags,
                size_bytes: img.size.max(0) as u64,
                created: chrono::DateTime::from_timestamp(img.created, 0).unwrap_or_default(),
                containers: img.containers,
                project,
                service,
            }
        })
        .collect();
    let volumes: Vec<DockerVolumeInfo> = df
        .volumes
        .unwrap_or_default()
        .into_iter()
        .map(|v| {
            let ref_count = v.usage_data.as_ref().map(|u| u.ref_count).unwrap_or(-1);
            DockerVolumeInfo {
                name: v.name,
                driver: v.driver,
                mountpoint: v.mountpoint,
                in_use: ref_count > 0,
                ref_count,
                size_bytes: v.usage_data.map(|u| u.size).unwrap_or(-1),
            }
        })
        .collect();
    Ok((images, volumes))
}

/// Lists every network on the host. `in_use` is computed by cross-referencing
/// every container's attached networks (by name) — the plain network-list
/// endpoint never populates its own `Containers` field (only `network
/// inspect` does, and doing that per-network would be an N+1 round trip).
/// Served from the TTL cache (`state.docker_cache.networks`).
pub async fn list_networks(state: AppState) -> RpResponse {
    match state
        .docker_cache
        .networks
        .get_or_refresh(|| compute_networks(&state))
        .await
    {
        Ok(infos) => RpResponse::DockerNetworks(infos),
        Err(e) => RpResponse::err("RuntimeError", e),
    }
}

/// The cache miss-path of [`list_networks`]: lists networks and cross-references
/// container attachments to compute each network's in-use count.
async fn compute_networks(state: &AppState) -> Result<Vec<DockerNetworkInfo>, String> {
    use bollard::{container::ListContainersOptions, network::ListNetworksOptions};

    let networks = state
        .docker
        .inner
        .list_networks(None::<ListNetworksOptions<String>>)
        .await
        .map_err(|e| e.to_string())?;

    let containers = state
        .docker
        .inner
        .list_containers(Some(ListContainersOptions::<String> {
            all: true,
            ..Default::default()
        }))
        .await
        .unwrap_or_default();
    let mut attached: HashMap<String, usize> = HashMap::new();
    for c in &containers {
        if let Some(nets) = c
            .network_settings
            .as_ref()
            .and_then(|ns| ns.networks.as_ref())
        {
            for name in nets.keys() {
                *attached.entry(name.clone()).or_insert(0) += 1;
            }
        }
    }

    let idx = ServiceIndex::build(state).await;
    Ok(networks
        .into_iter()
        .map(|n| {
            let name = n.name.unwrap_or_default();
            let container_count = attached.get(&name).copied().unwrap_or(0);
            DockerNetworkInfo {
                id: n.id.unwrap_or_default(),
                project: idx.network_project(&name),
                name,
                driver: n.driver.unwrap_or_default(),
                scope: n.scope.unwrap_or_default(),
                in_use: container_count > 0,
                container_count,
            }
        })
        .collect())
}

/// Lists every container on the host (running + stopped) for the Docker tab's
/// Containers sub-tab. Host-wide, não só rustploy: `managed`/`project`/`service`
/// são atribuição best-effort pelo label `rustploy.service_id` (exato, quando
/// presente). Não é cacheado — estado de container muda a cada start/stop.
pub async fn list_containers(state: AppState) -> RpResponse {
    use bollard::container::ListContainersOptions;
    let containers = match state
        .docker
        .inner
        .list_containers(Some(ListContainersOptions::<String> {
            all: true,
            ..Default::default()
        }))
        .await
    {
        Ok(c) => c,
        Err(e) => return RpResponse::err("RuntimeError", e.to_string()),
    };
    let idx = ServiceIndex::build(&state).await;
    let orphans = OrphanIndex::build(&state).await;
    let infos: Vec<DockerContainerInfo> = containers
        .into_iter()
        .map(|c| {
            let name = c
                .names
                .as_ref()
                .and_then(|n| n.first())
                .map(|n| n.trim_start_matches('/').to_string())
                .unwrap_or_default();
            let labels = c.labels.unwrap_or_default();
            let managed = labels
                .get("rustploy.managed")
                .map(|v| v == "true")
                .unwrap_or(false);
            let (project, service) = labels
                .get("rustploy.service_id")
                .and_then(|sid| idx.by_service_id.get(sid))
                .map(|(p, s)| (Some(p.clone()), Some(s.clone())))
                .unwrap_or((None, None));
            let removed_in_git = orphans.lookup(&labels);
            DockerContainerInfo {
                id: c.id.unwrap_or_default(),
                name,
                image: c.image.unwrap_or_default(),
                state: c.state.unwrap_or_default(),
                status: c.status.unwrap_or_default(),
                managed,
                project,
                service,
                removed_in_git,
            }
        })
        .collect();
    RpResponse::DockerContainers(infos)
}

/// Stops every rustploy-managed service, regardless of what the DB's status
/// column currently claims — reuses `service_stop::handle` (which does the
/// real Docker-level container lookup by label/name, not just
/// `live_container_id`) instead of only touching services already marked
/// `Running`/`Degraded`, so nothing is missed due to state drift. Scoped to
/// rustploy's own services; never touches unrelated containers on the host.
pub async fn stop_all_managed(state: AppState) -> RpResponse {
    let services = match crate::store::services::list_all(&state.db).await {
        Ok(s) => s,
        Err(e) => return RpResponse::err("DatabaseError", e.to_string()),
    };
    let mut count = 0u32;
    for svc in services {
        if matches!(svc.status, ServiceStatus::Stopped) {
            continue;
        }
        let resp = crate::features::deploy::stop::handle(state.deploy_ctx(), svc.id).await;
        if matches!(resp, RpResponse::Ok) {
            count += 1;
        }
    }
    RpResponse::StopAllResult { count }
}

#[cfg(test)]
mod orphan_tests {
    use super::*;

    fn labels(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn orfao_e_reconhecido_pelo_id_e_pela_stack_compose() {
        let mut o = OrphanIndex::default();
        o.by_service_id.insert("svc_api".into(), "api".into());
        o.by_compose_project
            .insert("rp_ab12cd34_db".into(), "banco".into());
        assert_eq!(
            o.lookup(&labels(&[("rustploy.service_id", "svc_api")]))
                .as_deref(),
            Some("api")
        );
        assert_eq!(
            o.lookup(&labels(&[("com.docker.compose.project", "rp_ab12cd34_db")]))
                .as_deref(),
            Some("banco")
        );
        // o que não é órfão não ganha marca
        assert_eq!(
            o.lookup(&labels(&[("rustploy.service_id", "svc_vivo")])),
            None
        );
        assert_eq!(o.lookup(&labels(&[])), None);
    }
}