shiguredo_container 2026.1.0-canary.8

Runtime-agnostic container library for Rust on macOS and Linux
Documentation
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
//! `ContainerRequest` と関連型。
//! testcontainers-rs 0.27 のサブセット (差分の正は `docs/TESTCONTAINERS.md`)。

use std::{
    borrow::Cow,
    collections::BTreeMap,
    fmt::{Debug, Formatter},
    net::IpAddr,
    time::Duration,
};

use crate::{
    Error, Image,
    core::{
        ContainerState, copy::CopyToContainer, healthcheck::Healthcheck, image::exec::ExecCommand,
        logs::consumer::LogConsumer, mounts::Mount, ports::ContainerPort, wait::WaitFor,
    },
};

/// 起動待機 (ready_conditions) の既定タイムアウト。
///
/// start 側 (`run_ready_sequence`) と exec 側 (`ContainerAsync::exec`) で共用する。
/// `ContainerRequest::startup_timeout` 未設定時にこの値が使われる。
pub(crate) const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(60);

/// コンテナ起動のリクエスト。`Image` に設定を重ねて作る。
#[must_use]
pub struct ContainerRequest<I: Image> {
    pub(crate) image: I,
    pub(crate) overridden_cmd: Vec<String>,
    pub(crate) image_name: Option<String>,
    pub(crate) image_tag: Option<String>,
    pub(crate) container_name: Option<String>,
    pub(crate) hostname: Option<String>,
    pub(crate) network: Option<String>,
    pub(crate) labels: BTreeMap<String, String>,
    pub(crate) env_vars: BTreeMap<String, String>,
    pub(crate) hosts: BTreeMap<String, ExtraHost>,
    pub(crate) mounts: Vec<Mount>,
    pub(crate) health_check: Option<Healthcheck>,
    pub(crate) copy_to_sources: Vec<CopyToContainer>,
    pub(crate) ports: Option<Vec<PortMapping>>,
    pub(crate) privileged: bool,
    pub(crate) readonly_rootfs: bool,
    pub(crate) cap_add: Option<Vec<String>>,
    pub(crate) cap_drop: Option<Vec<String>>,
    pub(crate) shm_size: Option<u64>,
    pub(crate) ready_conditions: Option<Vec<WaitFor>>,
    pub(crate) startup_timeout: Option<Duration>,
    pub(crate) working_dir: Option<String>,
    pub(crate) user: Option<String>,
    pub(crate) open_stdin: Option<bool>,
    pub(crate) log_consumers: Vec<Box<dyn LogConsumer + 'static>>,
    pub(crate) init: bool,
    pub(crate) platform: Option<String>,
    pub(crate) ssh: bool,
    pub(crate) masked_paths: Option<Vec<String>>,
    pub(crate) readonly_paths: Option<Vec<String>>,
}

/// ポートマッピング。
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PortMapping {
    pub(crate) host_port: u16,
    pub(crate) container_port: ContainerPort,
}

/// extra_hosts 用のホスト指定。
#[derive(Debug, Clone, Copy)]
pub enum ExtraHost {
    /// 固定の IP アドレス。
    Addr(IpAddr),
    /// ホストのゲートウェイアドレス (Docker の `host-gateway` 相当)。
    HostGateway,
}

// 本家 testcontainers-rs と同じ公開 API。macOS 経路では match で直接分解しており本 impl を経由しないが、
// Linux (Docker) 経路の extra_hosts 変換で利用するため意図的に保持する。
impl std::fmt::Display for ExtraHost {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExtraHost::Addr(a) => write!(f, "{a}"),
            ExtraHost::HostGateway => write!(f, "host-gateway"),
        }
    }
}

impl<I: Image> ContainerRequest<I> {
    /// イメージを返す。
    pub fn image(&self) -> &I {
        &self.image
    }

    /// ネットワーク名を返す。
    pub fn network(&self) -> &Option<String> {
        &self.network
    }

    /// ラベル一覧を返す。
    pub fn labels(&self) -> &BTreeMap<String, String> {
        &self.labels
    }

    /// コンテナ名を返す。
    pub fn container_name(&self) -> &Option<String> {
        &self.container_name
    }

    /// ホスト名を返す。
    pub fn hostname(&self) -> Option<&str> {
        self.hostname.as_deref()
    }

    /// 環境変数を返す。`Image::env_vars` とリクエスト側の設定をマージした結果。
    pub fn env_vars(&self) -> impl Iterator<Item = (Cow<'_, str>, Cow<'_, str>)> {
        self.image
            .env_vars()
            .into_iter()
            .map(|(name, val)| (name.into(), val.into()))
            .chain(
                self.env_vars
                    .iter()
                    .map(|(name, val)| (name.into(), val.into())),
            )
    }

    /// extra_hosts エントリを返す。
    pub fn hosts(&self) -> impl Iterator<Item = (Cow<'_, str>, &ExtraHost)> {
        self.hosts.iter().map(|(name, host)| (name.into(), host))
    }

    /// マウント一覧を返す。`Image::mounts` とリクエスト側の設定を連結した結果。
    pub fn mounts(&self) -> impl Iterator<Item = &Mount> {
        self.image.mounts().into_iter().chain(self.mounts.iter())
    }

    /// ヘルスチェック設定を返す。
    pub fn health_check(&self) -> Option<&Healthcheck> {
        self.health_check.as_ref()
    }

    /// コンテナへコピーするファイル一覧を返す。
    pub fn copy_to_sources(&self) -> impl Iterator<Item = &CopyToContainer> {
        self.image
            .copy_to_sources()
            .into_iter()
            .chain(self.copy_to_sources.iter())
    }

    /// ポートマッピング一覧を返す。
    pub fn ports(&self) -> Option<&Vec<PortMapping>> {
        self.ports.as_ref()
    }

    /// privileged モードかどうかを返す。
    pub fn privileged(&self) -> bool {
        self.privileged
    }

    /// ルートファイルシステムが読み取り専用かどうかを返す。
    pub fn readonly_rootfs(&self) -> bool {
        self.readonly_rootfs
    }

    /// 追加する Linux capability 一覧を返す。
    pub fn cap_add(&self) -> Option<&Vec<String>> {
        self.cap_add.as_ref()
    }

    /// 削除する Linux capability 一覧を返す。
    pub fn cap_drop(&self) -> Option<&Vec<String>> {
        self.cap_drop.as_ref()
    }

    /// /dev/shm のサイズ (バイト) を返す。
    pub fn shm_size(&self) -> Option<u64> {
        self.shm_size
    }

    /// entrypoint を返す。
    pub fn entrypoint(&self) -> Option<&str> {
        self.image.entrypoint()
    }

    /// CMD を返す。`overridden_cmd` が非空ならそれを、空なら `Image::cmd` を返す。
    pub fn cmd(&self) -> impl Iterator<Item = Cow<'_, str>> {
        // `either` クレートに依存せず、自前で切り替える。
        // `overridden_cmd` が空なら `image.cmd()` を使う。
        if !self.overridden_cmd.is_empty() {
            let front: Vec<Cow<'_, str>> = self.overridden_cmd.iter().map(Cow::from).collect();
            CmdIter {
                front: front.into_iter(),
                back: Vec::new().into_iter(),
            }
        } else {
            let back: Vec<Cow<'_, str>> = self.image.cmd().into_iter().map(Into::into).collect();
            CmdIter {
                front: Vec::new().into_iter(),
                back: back.into_iter(),
            }
        }
    }

    /// イメージの descriptor (`name:tag` 形式) を返す。
    pub fn descriptor(&self) -> String {
        let original_name = self.image.name();
        let original_tag = self.image.tag();

        let name = self.image_name.as_deref().unwrap_or(original_name);
        let tag = self.image_tag.as_deref().unwrap_or(original_tag);

        format!("{name}:{tag}")
    }

    /// 準備完了条件を返す。リクエスト側の設定が優先、未設定なら `Image::ready_conditions`。
    pub fn ready_conditions(&self) -> Vec<WaitFor> {
        self.ready_conditions
            .clone()
            .unwrap_or_else(|| self.image.ready_conditions())
    }

    /// 公開ポート一覧を返す。
    pub fn expose_ports(&self) -> &[ContainerPort] {
        self.image.expose_ports()
    }

    /// 起動後に実行するコマンドを返す。
    pub fn exec_after_start(
        &self,
        cs: ContainerState,
    ) -> std::result::Result<Vec<ExecCommand>, Error> {
        self.image.exec_after_start(cs)
    }

    /// 起動タイムアウトを返す。
    pub fn startup_timeout(&self) -> Option<Duration> {
        self.startup_timeout
    }

    /// 作業ディレクトリを返す。
    pub fn working_dir(&self) -> Option<&str> {
        self.working_dir.as_deref()
    }

    /// 実行ユーザーを返す。
    pub fn user(&self) -> Option<&str> {
        self.user.as_deref()
    }

    /// stdin を開くかどうかを返す。
    pub fn open_stdin(&self) -> Option<bool> {
        self.open_stdin
    }

    /// init プロセスが有効かどうかを返す。
    pub fn init(&self) -> bool {
        self.init
    }

    /// プラットフォーム指定を返す。
    pub fn platform(&self) -> &Option<String> {
        &self.platform
    }

    /// SSH 転送が有効かどうかを返す。
    pub fn ssh(&self) -> bool {
        self.ssh
    }

    /// OCI `maskedPaths` (Apple container 1.2.0 以上) を返す。
    ///
    /// `None` はランタイム既定セット、`Some(vec![])` は既定の無効化、
    /// 明示リストは既定を完全に上書きする。
    pub fn masked_paths(&self) -> Option<&Vec<String>> {
        self.masked_paths.as_ref()
    }

    /// OCI `readonlyPaths` (Apple container 1.2.0 以上) を返す。
    ///
    /// `None` はランタイム既定、`Some(vec![])` は既定の無効化、
    /// 明示リストは既定を完全に上書きする。
    pub fn readonly_paths(&self) -> Option<&Vec<String>> {
        self.readonly_paths.as_ref()
    }
}

impl<I: Image> From<I> for ContainerRequest<I> {
    fn from(image: I) -> Self {
        Self {
            image,
            overridden_cmd: Vec::new(),
            image_name: None,
            image_tag: None,
            container_name: None,
            hostname: None,
            network: None,
            labels: BTreeMap::default(),
            env_vars: BTreeMap::default(),
            hosts: BTreeMap::default(),
            mounts: Vec::new(),
            health_check: None,
            copy_to_sources: Vec::new(),
            ports: None,
            privileged: false,
            readonly_rootfs: false,
            cap_add: None,
            cap_drop: None,
            shm_size: None,
            ready_conditions: None,
            startup_timeout: None,
            working_dir: None,
            user: None,
            open_stdin: None,
            log_consumers: vec![],
            init: false,
            platform: None,
            ssh: false,
            masked_paths: None,
            readonly_paths: None,
        }
    }
}

impl PortMapping {
    pub(crate) fn new(local: u16, internal: ContainerPort) -> Self {
        Self {
            host_port: local,
            container_port: internal,
        }
    }

    /// ホスト側のポート番号を返す。
    pub fn host_port(&self) -> u16 {
        self.host_port
    }

    /// コンテナ側のポートを返す。
    pub fn container_port(&self) -> ContainerPort {
        self.container_port
    }
}

/// 同一コンテナポート (proto 込み) への重複マッピングを検出してエラーにする。
///
/// `with_mapped_port(8080, 80.tcp()).with_mapped_port(8081, 80.tcp())` のように
/// 同一コンテナポートへ複数のホストポートをマッピングすると、Linux の
/// `build_port_bindings` は後勝ちで 1 本だけを送信し (先のマッピングが黙って消える)、
/// macOS の `build_config` は重複 `PortCfg` をそのまま XPC に送る。
/// 黙って潰れる挙動をなくすため、pull 前検証 (Linux は `linux_unsupported_request_reason` の
/// 直後、macOS は `reject_sctp_ports` の直後) で明示エラーにする (fail-fast)。
///
/// 判定は `ContainerPort` 完全一致 (proto 込み)。同番号・異プロトコルは別エントリ
/// として共存させる (既存の mapped vs expose の異プロトコル共存テスト
/// `different_protocol_same_number_keeps_both` を維持)。
///
/// ホストポート側の重複 (同一ホストポートへの複数マッピング) はこの関数の対象外。
/// macOS は `build_config` が `duplicate host port mapping` で、Linux は Docker が
/// `port is already allocated` で明示エラーにする。
pub(crate) fn reject_duplicate_mapped_ports(
    ports: &[PortMapping],
) -> crate::core::error::Result<()> {
    let mut seen: BTreeMap<ContainerPort, u16> = BTreeMap::new();
    for p in ports {
        if let Some(previous) = seen.insert(p.container_port, p.host_port) {
            return Err(Error::other(format!(
                "duplicate container port mapping: container port {} is mapped to \
                 both host ports {previous} and {}",
                p.container_port, p.host_port
            )));
        }
    }
    Ok(())
}

impl<I: Image + Debug> Debug for ContainerRequest<I> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut repr = f.debug_struct("ContainerRequest");
        repr.field("image", &self.image)
            .field("overridden_cmd", &self.overridden_cmd)
            .field("image_name", &self.image_name)
            .field("image_tag", &self.image_tag)
            .field("container_name", &self.container_name)
            .field("hostname", &self.hostname)
            .field("network", &self.network)
            .field("labels", &self.labels)
            .field("env_vars", &self.env_vars)
            .field("hosts", &self.hosts)
            .field("mounts", &self.mounts)
            .field("health_check", &self.health_check)
            .field("ports", &self.ports)
            .field("privileged", &self.privileged)
            .field("readonly_rootfs", &self.readonly_rootfs)
            .field("cap_add", &self.cap_add)
            .field("cap_drop", &self.cap_drop)
            .field("shm_size", &self.shm_size)
            .field("startup_timeout", &self.startup_timeout)
            .field("working_dir", &self.working_dir)
            .field("user", &self.user)
            .field("open_stdin", &self.open_stdin)
            .field("init", &self.init)
            .field("platform", &self.platform)
            .field("ssh", &self.ssh)
            .field("masked_paths", &self.masked_paths)
            .field("readonly_paths", &self.readonly_paths);
        repr.finish()
    }
}

/// `cmd` のイテレーター。`overridden_cmd` が空なら `image.cmd()` に切り替える。
/// `either` クレートに依存しないための自前実装。
pub(crate) struct CmdIter<'a> {
    pub(crate) front: std::vec::IntoIter<Cow<'a, str>>,
    pub(crate) back: std::vec::IntoIter<Cow<'a, str>>,
}

impl<'a> Iterator for CmdIter<'a> {
    type Item = Cow<'a, str>;

    fn next(&mut self) -> Option<Self::Item> {
        self.front.next().or_else(|| self.back.next())
    }
}

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

    #[test]
    fn reject_duplicate_mapped_ports_detects_same_container_port() {
        // 同一コンテナポート (proto 込み) への重複マッピングはエラーになること。
        let ports = vec![
            PortMapping::new(8080, ContainerPort::Tcp(80)),
            PortMapping::new(8081, ContainerPort::Tcp(80)),
        ];
        let err = reject_duplicate_mapped_ports(&ports).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("duplicate container port mapping"),
            "エラーに duplicate container port mapping を含むこと: {msg}"
        );
        assert!(
            msg.contains("80/tcp"),
            "エラーにコンテナポートを含むこと: {msg}"
        );
        assert!(
            msg.find("8080")
                .expect("先に登録したホストポート 8080 が現れること")
                < msg
                    .find("8081")
                    .expect("後に登録したホストポート 8081 が現れること"),
            "先に登録したホストポートが先に現れること: {msg}"
        );
    }

    #[test]
    fn reject_duplicate_mapped_ports_detects_identical_mapping() {
        // 完全同一のマッピング (同一ホストポート + 同一コンテナポート) もエラーになること。
        let ports = vec![
            PortMapping::new(8080, ContainerPort::Tcp(80)),
            PortMapping::new(8080, ContainerPort::Tcp(80)),
        ];
        reject_duplicate_mapped_ports(&ports).expect_err("完全同一マッピングも重複であること");
    }

    #[test]
    fn reject_duplicate_mapped_ports_detects_triple_mapping() {
        // 3 重以上の重複もエラーになること (最初の競合ペアを報告する)。
        let ports = vec![
            PortMapping::new(8080, ContainerPort::Tcp(80)),
            PortMapping::new(8081, ContainerPort::Tcp(80)),
            PortMapping::new(8082, ContainerPort::Tcp(80)),
        ];
        let err = reject_duplicate_mapped_ports(&ports).unwrap_err();
        assert!(
            err.to_string().contains("8080") && err.to_string().contains("8081"),
            "最初の競合ペア (8080 / 8081) を報告すること: {err}"
        );
    }

    #[test]
    fn reject_duplicate_mapped_ports_detects_sctp_duplicate() {
        // SCTP 同士の重複も検出されること (Linux ではこの経路が実経路になる)。
        let ports = vec![
            PortMapping::new(8080, ContainerPort::Sctp(80)),
            PortMapping::new(8081, ContainerPort::Sctp(80)),
        ];
        reject_duplicate_mapped_ports(&ports).expect_err("SCTP の重複もエラーになること");
    }

    #[test]
    fn reject_duplicate_mapped_ports_keeps_different_protocol() {
        // 同番号・異プロトコルは別エントリとして共存できること。
        let ports = vec![
            PortMapping::new(8080, ContainerPort::Tcp(80)),
            PortMapping::new(8081, ContainerPort::Udp(80)),
            PortMapping::new(8082, ContainerPort::Sctp(80)),
        ];
        reject_duplicate_mapped_ports(&ports).expect("異プロトコルは重複とみなさないこと");
    }

    #[test]
    fn reject_duplicate_mapped_ports_accepts_single_mapping() {
        // 単一マッピングはエラーにならないこと。
        let ports = vec![PortMapping::new(8080, ContainerPort::Tcp(80))];
        reject_duplicate_mapped_ports(&ports).expect("単一マッピングはエラーにならないこと");
    }

    #[test]
    fn reject_duplicate_mapped_ports_accepts_empty() {
        // 空リストはエラーにならないこと。
        reject_duplicate_mapped_ports(&[]).expect("空リストはエラーにならないこと");
    }
}