Struct Container

Source
pub struct Container { /* private fields */ }
Expand description

Interface for accessing and manipulating Podman Container.

Api Reference

Implementations§

Source§

impl Container

Source

pub fn new(podman: Podman, id: impl Into<Id>) -> Self

Exports an interface exposing operations against a Container instance.

Source

pub fn id(&self) -> &Id

A getter for Container id

Source§

impl Container

Source

pub async fn start(&self, detach_keys: Option<String>) -> Result<()>

Api Reference

Start this container.

Parameters:

  • detach_keys - Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl- where is one of: a-z, @, ^, [, , or _.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").start(None).await {
        eprintln!("{}", e);
    }
};
Source

pub async fn stop(&self, opts: &ContainerStopOpts) -> Result<()>

Api Reference

Stop this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").stop(&Default::default()).await {
        eprintln!("{}", e);
    }
};
Source

pub async fn inspect(&self) -> Result<ContainerInspectResponseLibpod>

Api Reference

Return low-level information about this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("79c93f220e3e").inspect().await {
        Ok(info) => println!("{:?}", info),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub async fn send_signal(&self, signal: impl Into<String>) -> Result<()>

Api Reference

Send a signal to this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").send_signal("INT").await {
        eprintln!("{}", e);
    }
};
Source

pub async fn kill(&self) -> Result<()>

Api Reference

Kill this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").kill().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn pause(&self) -> Result<()>

Api Reference

Use the cgroups freezer to suspend all processes in this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").pause().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn unpause(&self) -> Result<()>

Api Reference

Unpause this container

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").unpause().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn restart_with_timeout(&self, t: usize) -> Result<()>

Api Reference

Restart this container with a timeout.

Parameters:

  • t - number of seconds to wait before killing the container

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").restart_with_timeout(20).await {
        eprintln!("{}", e);
    }
};
Source

pub async fn restart(&self) -> Result<()>

Api Reference

Restart this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").restart().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn delete(&self, opts: &ContainerDeleteOpts) -> Result<()>

Api Reference

Delete this container.

Examples:

async {
    use podman_api::Podman;
    use podman_api::opts::ContainerDeleteOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman
        .containers()
        .get("79c93f220e3e")
        .delete(&ContainerDeleteOpts::builder().volumes(true).build())
        .await
    {
        eprintln!("{}", e);
    }
};
Source

pub async fn remove(&self) -> Result<()>

Api Reference

Force remove this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").remove().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn mount(&self) -> Result<PathBuf>

Api Reference

Mount this container to the filesystem.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("79c93f220e3e").mount().await {
        Ok(path) => println!("mounted container path {}", path.display()),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub async fn unmount(&self) -> Result<()>

Api Reference

Unmount this container from the filesystem.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").unmount().await {
        eprintln!("{}", e);
    }
};
Source

pub fn checkpoint_export( &self, opts: &ContainerCheckpointOpts, ) -> impl Stream<Item = Result<Vec<u8>>> + Unpin + '_

Api Reference

Checkpoint this container returning the checkpoint image in a tar.gz.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    use podman_api::opts::ContainerCheckpointOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("79c93f220e3e");
    let mut export_stream = container.checkpoint_export(
        &ContainerCheckpointOpts::builder()
            .print_stats(true)
            .build(),
    );

    while let Some(tar_gz_chunk) = export_stream.next().await {
        println!("{:?}", tar_gz_chunk);
    }
};
Source

pub async fn checkpoint(&self, opts: &ContainerCheckpointOpts) -> Result<Value>

Api Reference

Checkpoint this container.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    use podman_api::opts::ContainerCheckpointOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("79c93f220e3e");
    let mut export_stream = container.checkpoint_export(
        &ContainerCheckpointOpts::builder()
            .print_stats(true)
            .build(),
    );

    while let Some(tarball_chunk) = export_stream.next().await {
        println!("{:?}", tarball_chunk);
    }
};
Source

pub async fn commit(&self, opts: &ContainerCommitOpts) -> Result<()>

Api Reference

Create a new image from this container.

Examples:

async {
    use podman_api::Podman;
    use podman_api::opts::ContainerCommitOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman
        .containers()
        .get("79c93f220e3e")
        .commit(
            &ContainerCommitOpts::builder()
                .pause(true)
                .repo("image-name")
                .tag("1.0.0")
                .build(),
        )
        .await
    {
        eprintln!("{}", e);
    }
};
Source

pub async fn create_exec(&self, opts: &ExecCreateOpts) -> Result<Exec>

Api Reference

Create an exec session to run a command inside this container. Exec sessions will be automatically removed 5 minutes after they exit.

This endpoint only creates the exec. To start it use Exec::start.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let exec = podman
    .containers()
    .get("79c93f220e3e")
    .create_exec(
        &podman_api::opts::ExecCreateOpts::builder()
            .command(["cat", "/some/path/in/container"])
            .attach_stdout(true)
            .attach_stderr(true)
            .build(),
    )
    .await
    .unwrap();
};
Source

pub async fn rename(&self, new_name: impl AsRef<str>) -> Result<()>

Api Reference

Change the name of this container.

Parameters:

  • new_name - new name to give for this container

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").rename("my-container").await {
        eprintln!("{}", e);
    }
};
Source

pub async fn init(&self) -> Result<()>

Api Reference

Performs all tasks necessary for initializing the container but does not start the container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("79c93f220e3e").init().await {
        eprintln!("{}", e);
    }
};
Source

pub async fn wait(&self, opts: &ContainerWaitOpts) -> Result<()>

Api Reference

Wait for this container to meet a given condition.

Examples:

async {
    use podman_api::Podman;
    use podman_api::opts::ContainerWaitOpts;
    use podman_api::models::ContainerStatus;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman
        .containers()
        .get("79c93f220e3e")
        .wait(
            &ContainerWaitOpts::builder()
                .conditions([ContainerStatus::Configured])
                .interval("300ms")
                .build(),
        )
        .await
    {
        eprintln!("{}", e);
    }
};
Source

pub async fn exists(&self) -> Result<bool>

Api Reference

Quick way to determine if a container exists by name or ID

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("79c93f220e3e").exists().await {
        Ok(exists) => if exists {
            println!("container exists!");
        } else {
            println!("container doesn't exists!");
        },
        Err(e) => eprintln!("check failed: {}", e),
    }
};
Source

pub async fn attach( &self, opts: &ContainerAttachOpts, ) -> Result<Multiplexer<'_>>

Api Reference

Attach to this container.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");
    let container = podman.containers().get("79c93f220e3e");
    let tty_multiplexer = container
            .attach(&Default::default())
            .await
            .unwrap();
    let (mut reader, _writer) = tty_multiplexer.split();

    while let Some(tty_result) = reader.next().await {
        match tty_result {
            Ok(chunk) => println!("{:?}", chunk),
            Err(e) => eprintln!("Error: {}", e),
        }
    }
};
Source

pub async fn changes( &self, opts: &ChangesOpts, ) -> Result<Vec<ContainerChangeResponseItem>>

Api Reference

Returns which files in this container’s filesystem have been added, deleted, or modified.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman
        .containers()
        .get("79c93f220e3e")
        .changes(&Default::default())
        .await
    {
        Ok(changes) => println!("{:?}", changes),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub fn logs( &self, opts: &ContainerLogsOpts, ) -> impl Stream<Item = Result<TtyChunk>> + '_

Api Reference

Get logs from this container.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    use podman_api::conn::TtyChunk;
    use podman_api::opts::ContainerLogsOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("3f278d2d0d79");
    let mut logs = container.logs(
        &ContainerLogsOpts::builder()
            .stdout(true)
            .stderr(true)
            .follow(true)
            .build(),
    );

    while let Some(chunk) = logs.next().await {
        match chunk.unwrap() {
            TtyChunk::StdOut(data) => {
                println!("{}", String::from_utf8_lossy(&data));
            }
            TtyChunk::StdErr(data) => {
                eprintln!("{}", String::from_utf8_lossy(&data));
            }
            _ => {}
        }
    }
};
Source

pub async fn stats(&self) -> Result<ContainerStats200Response>

Api Reference

Return a single resource usage statistics of this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("fc93f220e3e").stats().await {
        Ok(stats) => println!("{:?}", stats),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub fn stats_stream( &self, interval: Option<usize>, ) -> impl Stream<Item = Result<ContainerStats200Response>> + '_

Api Reference

Return a stream of resource usage statistics of this container.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("fc93f220e3e");
    let mut stats = container.stats_stream(None);

    while let Some(chunk) = stats.next().await {
        match chunk {
            Ok(chunk) => println!("{:?}", chunk),
            Err(e) => eprintln!("{}", e),
        }
    }
};
Source

pub async fn top(&self, opts: &ContainerTopOpts) -> Result<ContainerTopOkBody>

Api Reference

List processes running inside this container.

Examples:

async {
    use podman_api::Podman;
};
async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("fc93f220e3e").top(&Default::default()).await {
        Ok(stats) => println!("{:?}", stats),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub fn top_stream( &self, opts: &ContainerTopOpts, ) -> impl Stream<Item = Result<ContainerTopOkBody>> + '_

Api Reference

List processes running inside this container as a stream. (As of libpod version 4.0)

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("fc93f220e3e");
    let mut top = container
        .top_stream(&Default::default());

    while let Some(chunk) = top.next().await {
        match chunk {
            Ok(chunk) => println!("{:?}", chunk),
            Err(e) => eprintln!("{}", e),
        }
    }
};
Source

pub async fn generate_systemd_units( &self, opts: &SystemdUnitsOpts, ) -> Result<Value>

Api Reference

Generate Systemd Units based on this container.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman
        .containers()
        .get("fc93f220e3e")
        .generate_systemd_units(&Default::default())
        .await
    {
        Ok(info) => println!("{:?}", info),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub async fn generate_kube_yaml(&self, service: bool) -> Result<String>

Api Reference

Generate Kubernetes YAML based on this container

Parameters:

  • service - Generate YAML for a Kubernetes service object.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman
        .containers()
        .get("fc93f220e3e")
        .generate_kube_yaml(false)
        .await
    {
        Ok(yaml) => println!("{:?}", yaml),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub async fn connect( &self, network: impl Into<Id>, opts: &NetworkConnectOpts, ) -> Result<()>

Api Reference

Connect this container to a network

Examples:

async {
    use podman_api::Podman;
    use podman_api::opts::NetworkConnectOpts;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman
            .containers()
            .get("fc93f220e3e")
            .connect("my-network", &Default::default())
            .await
    {
        eprintln!("{}", e);
    }
};
Source

pub async fn disconnect( &self, network: impl Into<Id>, force: bool, ) -> Result<()>

Api Reference

Disconnect this container from a network.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    if let Err(e) = podman.containers().get("fc93f220e3e").disconnect("my-network", true).await {
        eprintln!("{}", e);
    }
};
Source

pub async fn healthcheck(&self) -> Result<HealthCheckResults>

Api Reference

Execute the defined healthcheck and return information about the result.

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("fc93f220e3e").healthcheck().await {
        Ok(healthcheck) => println!("{:?}", healthcheck),
        Err(e) => eprintln!("{}", e),
    }
};
Source

pub fn copy_from( &self, path: impl AsRef<Path>, ) -> impl Stream<Item = Result<Vec<u8>>> + '_

Api Reference

Copy a file/folder from the container. The resulting stream is a tarball of the extracted files.

If path is not an absolute path, it is relative to the container’s root directory. The resource specified by path must exist. To assert that the resource is expected to be a directory, path should end in / or /. (assuming a path separator of /). If path ends in /. then this indicates that only the contents of the path directory should be copied. A symlink is always resolved to its target.

Examples:

async {
    use podman_api::Podman;
    use futures_util::TryStreamExt;
    use tar::Archive;

    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let bytes = podman
         .containers()
         .get("fc93f220e3e")
         .copy_from("/tmp/dir")
         .try_concat()
         .await.unwrap();

     let mut archive = Archive::new(&bytes[..]);
     let local_path = "/tmp";
     archive.unpack(&local_path).unwrap();
};
Source

pub async fn copy_to(&self, path: impl AsRef<Path>, body: Body) -> Result<()>

Api Reference

Copy a tarball (see body) to the container.

The tarball will be copied to the container and extracted at the given location (see path).

Examples:

async {
    use podman_api::Podman;
    use futures_util::TryStreamExt;
    use tar::Archive;

    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let bytes = vec![];
    let src_path = std::path::PathBuf::from("/tmp/dir");

    let mut ar = tar::Builder::new(Vec::new());
    let mut header = tar::Header::new_gnu();
    header.set_size(bytes.len() as u64);
    header.set_mode(0o0644);
    ar.append_data(
        &mut header,
        src_path
            .iter()
            .skip(1)
            .collect::<std::path::PathBuf>(),
        std::io::Cursor::new(bytes),
    ).unwrap();
    let data = ar.into_inner().unwrap();

    if let Err(e) = podman
        .containers()
        .get("fc93f220e3e")
        .copy_to("/", data.into())
        .await
    {
        eprintln!("Error: {}", e);
    }
};
Source

pub async fn copy_file_into<P: AsRef<Path>>( &self, path: P, bytes: &[u8], ) -> Result<()>

Api Reference

Copy a byte slice as file into (see bytes) the container.

The file will be copied at the given location (see path) and will be owned by root with access mask 644.

Examples:

async {
    use podman_api::Podman;
    use futures_util::TryStreamExt;
    use tar::Archive;

    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    use std::{fs::File, io::Read};

    let mut file = File::open("/some/important/file").unwrap();
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .expect("Cannot read file on the localhost.");

    if let Err(e) = podman
        .containers()
        .get("fc93f220e3e")
        .copy_file_into("/tmp/", &bytes)
        .await
    {
        eprintln!("Error: {}", e);
    }
};
Source

pub async fn resize(&self, width: usize, heigth: usize) -> Result<()>

Api Reference

Resize the terminal attached to this container (for use with Attach).

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");
    let container = podman.containers().get("451b27c6b9d3");

    if let Err(e) = container.resize(1280, 720).await {
        eprintln!("{}", e);
    }
};
Source

pub fn export(&self) -> impl Stream<Item = Result<Vec<u8>>> + Unpin + '_

Api Reference

Export the contents of a container as a tarball.

Examples:

use futures_util::StreamExt;
async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    let container = podman.containers().get("79c93f220e3e");
    let mut tarball_stream = container.export();
    let mut content = vec![];

    while let Some(tar_chunk) = tarball_stream.next().await {
        content.append(&mut tar_chunk.unwrap());
    }

    std::fs::write("/tmp/79c93f220e3e.tar", &content).unwrap();
};
Source

pub async fn restore(&self, opts: &ContainerRestoreOpts) -> Result<Value>

Api Reference

Restore a container from a checkpoint

Examples:

async {
    use podman_api::Podman;
    let podman = Podman::unix("/run/user/1000/podman/podman.sock");

    match podman.containers().get("79c93f220e3e").restore(&Default::default()).await {
        Ok(info) => println!("{info:?}"),
        Err(e) =>  eprintln!("{e}"),
    }
};

Trait Implementations§

Source§

impl Debug for Container

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T