furet 0.3.1

Postgres and ClickHouse per repo: tunnels, read-only remotes, rows you can follow, for you and your agents
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Databases running in Docker, found from `docker inspect`: usable without configuring anything.
//! Credentials come from the container's environment each time; nothing is written anywhere.

use crate::config::{Conn, Kind, Value};
use serde_json::Value as Json;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

#[derive(Debug, Clone)]
pub struct Found {
    pub name: String,
    pub container: String,
    pub conn: Conn,
    /// Started by this repo's compose file (or one of its worktrees').
    pub here: bool,
    /// The server's other databases (Postgres only, when asked for).
    pub databases: Vec<String>,
}

/// What Docker had, and why it couldn't be asked when it couldn't.
#[derive(Debug, Default)]
pub struct Detection {
    pub found: Vec<Found>,
    pub problem: Option<String>,
}

/// The docker CLI: on PATH, else where Docker Desktop, Homebrew, OrbStack, Rancher Desktop or
/// Colima put it (an app started from the Dock or a launcher has a minimal PATH).
fn docker_bin() -> Option<PathBuf> {
    if let Some(p) = std::env::var_os("FURET_DOCKER_BIN") {
        return Some(PathBuf::from(p));
    }
    if let Some(p) = std::env::var_os("PATH").and_then(|p| {
        std::env::split_paths(&p)
            .map(|d| d.join("docker"))
            .find(|f| f.is_file())
    }) {
        return Some(p);
    }
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_default();
    [
        PathBuf::from("/usr/local/bin/docker"),
        PathBuf::from("/opt/homebrew/bin/docker"),
        PathBuf::from("/Applications/Docker.app/Contents/Resources/bin/docker"),
        home.join(".orbstack/bin/docker"),
        home.join(".rd/bin/docker"),
        home.join(".docker/bin/docker"),
        PathBuf::from("/usr/bin/docker"),
        PathBuf::from("/snap/bin/docker"),
    ]
    .into_iter()
    .find(|p| p.is_file())
}

/// `docker …` with a deadline, so a stuck daemon can't stall the panel. Output is read while it
/// runs: `docker inspect` of a few containers is more than a pipe holds, and docker would block.
fn docker(bin: &Path, args: &[&str]) -> Result<String, String> {
    docker_within(bin, args, TIMEOUT)
}

fn docker_within(bin: &Path, args: &[&str], timeout: Duration) -> Result<String, String> {
    let mut cmd = Command::new(bin);
    // Credential helpers and contexts (Docker Desktop, OrbStack…) live next to the CLI.
    if let (Some(dir), Some(path)) = (bin.parent(), std::env::var_os("PATH")) {
        let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
        dirs.push(dir.to_path_buf());
        if let Ok(joined) = std::env::join_paths(dirs) {
            cmd.env("PATH", joined);
        }
    }
    let mut child = cmd
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("cannot run {}: {e}", bin.display()))?;
    let drain = |r: Option<Box<dyn std::io::Read + Send>>| {
        std::thread::spawn(move || {
            let mut s = String::new();
            if let Some(mut r) = r {
                let _ = r.read_to_string(&mut s);
            }
            s
        })
    };
    let out = drain(
        child
            .stdout
            .take()
            .map(|r| Box::new(r) as Box<dyn std::io::Read + Send>),
    );
    let err = drain(
        child
            .stderr
            .take()
            .map(|r| Box::new(r) as Box<dyn std::io::Read + Send>),
    );
    let start = std::time::Instant::now();
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Err(e) => return Err(e.to_string()),
            Ok(None) if start.elapsed() > timeout => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(format!(
                    "Docker didn't answer within {} s",
                    timeout.as_secs()
                ));
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
        }
    };
    let out = out.join().unwrap_or_default();
    if !status.success() {
        let err = err.join().unwrap_or_default();
        let err = err
            .lines()
            .find(|l| !l.trim().is_empty())
            .unwrap_or("")
            .trim()
            .to_string();
        return Err(
            if err.contains("Cannot connect to the Docker daemon")
                || err.contains("Is the docker daemon running")
                || err.contains("failed to connect to the docker API")
            {
                "Docker isn't running".into()
            } else {
                err
            },
        );
    }
    Ok(out)
}

const TIMEOUT: Duration = Duration::from_secs(10);

pub fn enabled() -> bool {
    !matches!(
        std::env::var("FURET_DOCKER").as_deref(),
        Ok("0") | Ok("false") | Ok("off")
    )
}

/// The running Postgres and ClickHouse containers; `roots` are the folders that count as this repo.
/// With `databases`, each Postgres server is also asked what other databases it holds.
pub fn running(roots: &[&Path], databases: bool) -> Detection {
    if !enabled() {
        return Detection::default();
    }
    let Some(bin) = docker_bin() else {
        return Detection {
            found: Vec::new(),
            problem: Some("docker not found (set FURET_DOCKER_BIN to its path)".into()),
        };
    };
    let ids = match docker(&bin, &["ps", "-q"]) {
        Ok(ids) => ids,
        Err(e) => {
            return Detection {
                found: Vec::new(),
                problem: Some(e),
            };
        }
    };
    let ids: Vec<&str> = ids.split_whitespace().collect();
    if ids.is_empty() {
        return Detection::default();
    }
    let mut args = vec!["inspect"];
    args.extend(&ids);
    let list = match docker(&bin, &args).map(|t| serde_json::from_str::<Json>(&t)) {
        Ok(Ok(Json::Array(list))) => list,
        Ok(_) => {
            return Detection {
                found: Vec::new(),
                problem: Some("unexpected docker inspect output".into()),
            };
        }
        Err(e) => {
            return Detection {
                found: Vec::new(),
                problem: Some(e),
            };
        }
    };
    let mut found: Vec<Found> = list.iter().filter_map(|c| self::found(c, roots)).collect();
    if databases {
        std::thread::scope(|s| {
            for f in found
                .iter_mut()
                .filter(|f| f.conn.kind == Some(Kind::Postgres))
            {
                let bin = &bin;
                s.spawn(move || f.databases = others(bin, f));
            }
        });
    }
    found.sort_by(|a, b| b.here.cmp(&a.here).then(a.name.cmp(&b.name)));
    Detection {
        found,
        problem: None,
    }
}

/// The databases of a Postgres container besides the one it was found with, asked with psql inside
/// it (its socket works whether or not the port is published). `postgres`, the maintenance
/// database, is left out; so is everything when the image has no psql or it doesn't answer.
fn others(bin: &Path, f: &Found) -> Vec<String> {
    let plain = |v: &Option<Value>| match v {
        Some(Value::Plain(s)) => s.clone(),
        _ => String::new(),
    };
    let (user, db) = (plain(&f.conn.user), plain(&f.conn.database));
    let pw = f
        .conn
        .password
        .as_ref()
        .map(|_| format!("PGPASSWORD={}", plain(&f.conn.password)));
    let mut args = vec!["exec"];
    if let Some(pw) = &pw {
        args.extend(["-e", pw]);
    }
    args.extend([
        "-e",
        "PGCONNECT_TIMEOUT=3",
        &f.container,
        "psql",
        "-X",
        "-A",
        "-t",
        "-U",
        &user,
        "-d",
        &db,
        "-c",
        "select datname from pg_database where datallowconn and not datistemplate order by 1",
    ]);
    docker_within(bin, &args, Duration::from_secs(5))
        .map(|out| {
            out.lines()
                .map(str::trim)
                .filter(|d| !d.is_empty() && *d != db && *d != "postgres")
                .map(String::from)
                .collect()
        })
        .unwrap_or_default()
}

/// The password of a container found earlier, for saving it: only if it still listens where the
/// saved connection will point, as the same user.
pub fn password(
    container: &str,
    host: &str,
    port: u16,
    user: &str,
) -> Result<Option<String>, String> {
    let bin = docker_bin().ok_or("docker not found (set FURET_DOCKER_BIN to its path)")?;
    let list: Json = serde_json::from_str(&docker(
        &bin,
        &["inspect", "--type", "container", container],
    )?)
    .map_err(|_| "unexpected docker inspect output".to_string())?;
    let f = list
        .get(0)
        .and_then(|c| found(c, &[]))
        .ok_or_else(|| format!("{container} isn't a database container anymore"))?;
    let plain = |v: &Option<Value>| match v {
        Some(Value::Plain(s)) => Some(s.clone()),
        _ => None,
    };
    if plain(&f.conn.host).as_deref() != Some(host)
        || f.conn.port != Some(port)
        || plain(&f.conn.user).as_deref() != Some(user)
    {
        return Err(format!(
            "{container} listens elsewhere or as another user: its password is only saved for {}@{}:{}",
            plain(&f.conn.user).unwrap_or_default(),
            plain(&f.conn.host).unwrap_or_default(),
            f.conn.port.unwrap_or_default()
        ));
    }
    Ok(plain(&f.conn.password))
}

/// Postgres or ClickHouse, from what only a server has: the port its image exposes (5432; 8123
/// for ClickHouse) or Postgres' `PGDATA`. Apps that connect to one carry `POSTGRES_*`/`CLICKHOUSE_*`
/// too, and some images are named after one (postgrest), so neither counts; a name only does when
/// the image exposes no ports at all. Poolers listen on 5432 too but only front a server that is
/// found on its own, under users of their own configuration, so they aren't databases.
fn kind_of(c: &Json, env: &[(&str, &str)]) -> Option<Kind> {
    let image = c["Config"]["Image"].as_str().unwrap_or("").to_lowercase();
    let has_data = env.iter().any(|(k, _)| *k == "PGDATA");
    if !has_data && POOLERS.iter().any(|p| image.contains(p)) {
        return None;
    }
    let ports = c["Config"]["ExposedPorts"].as_object();
    let exposes = |p: &str| ports.is_some_and(|m| m.contains_key(p));
    let none_exposed = ports.is_none_or(|m| m.is_empty());
    let named = |names: &[&str]| none_exposed && names.iter().any(|n| image.contains(n));
    if exposes("5432/tcp") || has_data || named(&["postgres", "postgis", "timescale"]) {
        Some(Kind::Postgres)
    } else if exposes("8123/tcp") || named(&["clickhouse"]) {
        Some(Kind::Clickhouse)
    } else {
        None
    }
}

const POOLERS: &[&str] = &[
    "pgbouncer",
    "pgcat",
    "odyssey",
    "pgpool",
    "supavisor",
    "pgdog",
];

fn found(c: &Json, roots: &[&Path]) -> Option<Found> {
    let image = c["Config"]["Image"].as_str()?;
    let env: Vec<(&str, &str)> = c["Config"]["Env"]
        .as_array()
        .map(|a| {
            a.iter()
                .filter_map(|e| e.as_str()?.split_once('='))
                .collect()
        })
        .unwrap_or_default();
    let kind = kind_of(c, &env)?;
    let var = |k: &str| {
        env.iter()
            .find(|(n, _)| *n == k)
            .map(|(_, v)| v.to_string())
            .filter(|v| !v.is_empty())
    };
    let labels = &c["Config"]["Labels"];
    let label = |k: &str| labels[k].as_str().map(String::from);
    let (inner, user, password, database) = match kind {
        Kind::Postgres => {
            let user = var("POSTGRES_USER").unwrap_or_else(|| "postgres".into());
            let db = var("POSTGRES_DB").unwrap_or_else(|| user.clone());
            (5432, user, var("POSTGRES_PASSWORD"), db)
        }
        Kind::Clickhouse => {
            let user = var("CLICKHOUSE_USER").unwrap_or_else(|| "default".into());
            (
                9000,
                user,
                var("CLICKHOUSE_PASSWORD"),
                var("CLICKHOUSE_DB").unwrap_or_else(|| "default".into()),
            )
        }
    };
    let container = c["Name"].as_str()?.trim_start_matches('/').to_string();
    let inside = |p: &str| {
        let p = Path::new(p);
        let p = p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
        p.is_absolute() && roots.iter().any(|r| p.starts_with(r))
    };
    let workdir = label("com.docker.compose.project.working_dir");
    let files = label("com.docker.compose.project.config_files");
    let here = workdir.as_deref().is_some_and(inside)
        && files
            .as_deref()
            .is_none_or(|f| f.split(',').all(|f| inside(f.trim())));
    let service = label("com.docker.compose.service");
    let name = match (&service, here) {
        (Some(s), true) => s.clone(),
        _ => container.clone(),
    };
    let project = label("com.docker.compose.project");
    let mut note = match (&project, here) {
        (Some(p), true) => format!("docker · {image} · this repo's compose ({p})"),
        (Some(p), false) => format!("docker · {image} · compose project {p}"),
        (None, _) => format!("docker · {image}"),
    };
    let address = address(c, inner);
    let unreachable = address.is_none().then(|| format!("port {inner} isn't published, so it can't be reached from this machine: publish it (ports: [\"{inner}:{inner}\"])"));
    if address.is_none() {
        note.push_str(&format!(" · port {inner} not published"));
    }
    let (host, port) = address.unwrap_or_else(|| ("localhost".into(), inner));
    let http_port = (kind == Kind::Clickhouse)
        .then(|| self::address(c, 8123))
        .flatten()
        .filter(|(h, _)| *h == host)
        .map(|(_, p)| p);
    Some(Found {
        name,
        container: container.clone(),
        here,
        databases: Vec::new(),
        conn: Conn {
            kind: Some(kind),
            host: Some(Value::Plain(host)),
            port: Some(port),
            http_port,
            user: Some(Value::Plain(user)),
            password: password.map(Value::Plain),
            database: Some(Value::Plain(database)),
            stage: Some("local".into()),
            note: Some(note),
            unreachable,
            container: Some(container),
            ..Conn::default()
        },
    })
}

/// Where the container's `inner` port can be reached: its published port, else (Linux only) its
/// address on the Docker network.
fn address(c: &Json, inner: u16) -> Option<(String, u16)> {
    let published = c["NetworkSettings"]["Ports"][format!("{inner}/tcp")]
        .as_array()
        .and_then(|b| {
            b.iter().find_map(|x| {
                let port = x["HostPort"].as_str()?.parse().ok()?;
                let ip = x["HostIp"].as_str().unwrap_or("");
                let host = if ip.is_empty() || ip == "0.0.0.0" || ip == "::" {
                    "localhost".to_string()
                } else {
                    ip.to_string()
                };
                Some((host, port))
            })
        });
    if published.is_some() || !cfg!(target_os = "linux") {
        return published;
    }
    c["NetworkSettings"]["Networks"]
        .as_object()?
        .values()
        .find_map(|n| {
            n["IPAddress"]
                .as_str()
                .filter(|ip| !ip.is_empty())
                .map(|ip| (ip.to_string(), inner))
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn container(image: &str, env: &[&str], ports: Json, labels: Json) -> Json {
        let exposed: serde_json::Map<String, Json> = ports
            .as_object()
            .map(|m| m.keys().map(|k| (k.clone(), json!({}))).collect())
            .unwrap_or_default();
        json!({
            "Name": "/proj-db-1",
            "Config": { "Image": image, "Env": env, "Labels": labels, "ExposedPorts": exposed },
            "NetworkSettings": { "Ports": ports, "Networks": { "bridge": { "IPAddress": "172.17.0.5" } } },
        })
    }

    #[test]
    fn reads_postgres_from_compose() {
        let c = container(
            "postgres:16-alpine",
            &[
                "POSTGRES_USER=app",
                "POSTGRES_PASSWORD=pw",
                "POSTGRES_DB=shop",
                "PATH=/usr/bin",
            ],
            json!({ "5432/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "5433" }] }),
            json!({ "com.docker.compose.service": "db", "com.docker.compose.project": "proj",
                    "com.docker.compose.project.working_dir": "/src/proj",
                    "com.docker.compose.project.config_files": "/src/proj/compose.yaml" }),
        );
        let f = found(&c, &[Path::new("/src/proj")]).unwrap();
        assert_eq!((f.name.as_str(), f.here), ("db", true));
        assert_eq!(f.conn.host, Some(Value::Plain("localhost".into())));
        assert_eq!(f.conn.port, Some(5433));
        assert_eq!(f.conn.password, Some(Value::Plain("pw".into())));
        assert_eq!(f.conn.database, Some(Value::Plain("shop".into())));
        let mut stray = c.clone();
        stray["Config"]["Labels"]["com.docker.compose.project.config_files"] =
            json!("/src/proj/compose.yaml,/tmp/override.yaml");
        assert!(!found(&stray, &[Path::new("/src/proj")]).unwrap().here);
        let elsewhere = found(&c, &[Path::new("/src/other")]).unwrap();
        assert_eq!(
            (elsewhere.name.as_str(), elsewhere.here),
            ("proj-db-1", false)
        );
    }

    #[test]
    fn defaults_and_other_images() {
        let c = container("clickhouse/clickhouse-server:24", &[], json!({}), json!({}));
        let f = found(&c, &[]).unwrap();
        assert_eq!(f.conn.kind, Some(Kind::Clickhouse));
        assert_eq!(f.conn.user, Some(Value::Plain("default".into())));
        if cfg!(target_os = "linux") {
            assert_eq!(
                (f.conn.host, f.conn.port),
                (Some(Value::Plain("172.17.0.5".into())), Some(9000))
            );
        }
        assert!(found(&container("redis:7", &[], json!({}), json!({})), &[]).is_none());
        let pg = found(
            &container("postgis/postgis:16", &[], json!({}), json!({})),
            &[],
        )
        .unwrap();
        assert_eq!(pg.conn.user, Some(Value::Plain("postgres".into())));
        assert_eq!(pg.conn.password, None);
    }

    /// The containers from a real `docker ps`: two compose projects, a plain one, Redpanda next to them.
    #[test]
    fn meteroid_setup() {
        let repo = "/src/meteroid-ent2";
        let compose = |project: &str, service: &str, dir: &str| {
            json!({
                "com.docker.compose.project": project, "com.docker.compose.service": service,
                "com.docker.compose.project.working_dir": dir,
                "com.docker.compose.project.config_files": format!("{dir}/docker/compose.yml"),
            })
        };
        let published = |inner: u16, host: u16| json!({ format!("{inner}/tcp"): [{ "HostIp": "0.0.0.0", "HostPort": host.to_string() }] });
        let mut db = container(
            "ghcr.io/meteroid-oss/meteroid-postgres:18.3-standard",
            &["POSTGRES_PASSWORD=secret"],
            published(5432, 15432),
            compose("meteroid-ent2", "meteroid-db", repo),
        );
        db["Name"] = json!("/meteroid-ent2-meteroid-db-1");
        let f = found(&db, &[Path::new(repo)]).unwrap();
        assert_eq!(
            (f.name.as_str(), f.here, f.conn.port),
            ("meteroid-db", true, Some(15432))
        );
        let mut ch = container(
            "clickhouse/clickhouse-server:25.6.2-alpine",
            &[],
            json!({
                "8123/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "18123" }],
                "9000/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "19000" }],
                "9009/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "19009" }],
            }),
            compose("meteroid-ent2", "clickhouse", repo),
        );
        ch["Name"] = json!("/meteroid-ent2-clickhouse-1");
        let f = found(&ch, &[Path::new(repo)]).unwrap();
        assert_eq!((f.conn.port, f.conn.http_port), (Some(19000), Some(18123)));
        let mut test_pg = container(
            "ghcr.io/meteroid-oss/meteroid-postgres:18.3-standard",
            &[],
            published(5432, 55432),
            json!({}),
        );
        test_pg["Name"] = json!("/meteroid-test-pg");
        assert_eq!(
            found(&test_pg, &[Path::new(repo)]).unwrap().name,
            "meteroid-test-pg"
        );
        let mut pgbouncer = container(
            "edoburu/pgbouncer:v1.23.1-p2",
            &[
                "DB_HOST=meteroid-db",
                "DB_USER=meteroid",
                "DB_PASSWORD=secret",
            ],
            json!({}),
            compose("meteroid-ent2", "pgbouncer", repo),
        );
        pgbouncer["Config"]["ExposedPorts"] = json!({ "5432/tcp": {} });
        assert!(
            found(&pgbouncer, &[Path::new(repo)]).is_none(),
            "a pooler fronts the database, it isn't one"
        );
        let redpanda = container(
            "docker.redpanda.com/redpandadata/console:v2.3.1",
            &[],
            published(8080, 18085),
            json!({}),
        );
        assert!(found(&redpanda, &[]).is_none());
    }

    #[test]
    fn recognises_custom_images_by_port_or_env_and_flags_unpublished_ones() {
        let mut custom = container("acme/db:1", &[], json!({}), json!({}));
        custom["Config"]["ExposedPorts"] = json!({ "5432/tcp": {} });
        let f = found(&custom, &[]).unwrap();
        assert_eq!(f.conn.kind, Some(Kind::Postgres));
        assert_eq!(f.conn.unreachable.is_some(), !cfg!(target_os = "linux"));
        let mut app = container(
            "meteroid/api:latest",
            &[
                "POSTGRES_HOST=meteroid-db",
                "POSTGRES_PASSWORD=x",
                "CLICKHOUSE_URL=http://clickhouse:8123",
            ],
            json!({}),
            json!({}),
        );
        app["Config"]["ExposedPorts"] = json!({ "8080/tcp": {} });
        assert!(
            found(&app, &[]).is_none(),
            "an app that connects to a database isn't one"
        );
        let mut postgrest = container("postgrest/postgrest:v12", &[], json!({}), json!({}));
        postgrest["Config"]["ExposedPorts"] = json!({ "3000/tcp": {} });
        assert!(found(&postgrest, &[]).is_none());
        let mut ch = container("acme/analytics:2", &[], json!({}), json!({}));
        ch["Config"]["ExposedPorts"] = json!({ "8123/tcp": {}, "9000/tcp": {} });
        assert_eq!(found(&ch, &[]).unwrap().conn.kind, Some(Kind::Clickhouse));
    }

    /// `docker inspect` of many containers outgrows a pipe: reading only after exit deadlocked.
    #[test]
    fn reads_output_larger_than_a_pipe() {
        let dir = std::env::temp_dir().join(format!("furet-fake-docker-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let bin = dir.join("docker");
        std::fs::write(&bin, "#!/bin/sh\nhead -c 300000 /dev/zero | tr '\\0' x\n").unwrap();
        std::fs::set_permissions(&bin, std::os::unix::fs::PermissionsExt::from_mode(0o755))
            .unwrap();
        let start = std::time::Instant::now();
        let out = docker(&bin, &["inspect"]).unwrap();
        assert_eq!(out.len(), 300000);
        assert!(start.elapsed() < Duration::from_secs(2));
        let _ = std::fs::remove_dir_all(dir);
    }
}