### NetworkCreateOptions::new example Source: https://docs.rs/dockworker/0.16.0/src/dockworker/network.rs.html Example of creating a network with options equivalent to the default bridge network. ```rust let network_name = "sample-network"; let mut opt = NetworkCreateOptions::new(network_name); opt.enable_icc() .enable_ip_masquerade() .host_binding_ipv4(Ipv4Addr::new(0, 0, 0, 0)) .bridge_name("docker0") .driver_mtu(1500); ``` -------------------------------- ### Start Container Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts a container. It can optionally be started with a specific checkpoint. ```APIDOC ## POST /containers/{id}/start ### Description Starts a container. It can optionally be started with a specific checkpoint. ### Method POST ### Endpoint /containers/{id}/start ### Parameters #### Query Parameters - **checkpoint** (string) - Required - The ID of the checkpoint to use for starting the container. - **checkpoint-dir** (string) - Optional - The directory containing the checkpoint. ### Request Example ```json { "example": "POST /containers/container_id/start?checkpoint=checkpoint_id&checkpoint-dir=checkpoint_directory" } ``` ### Response #### Success Response (204 No Content) Indicates the container was started successfully. ``` -------------------------------- ### Start Exec Instance Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts a previously set up exec instance. If detach is true, this endpoint returns immediately after starting the command. Otherwise, it sets up an interactive session with the command. ```APIDOC ## POST /exec/{id}/start ### Description Starts a previously set up exec instance. If detach is true, this endpoint returns immediately after starting the command. Otherwise, it sets up an interactive session with the command. ### Method POST ### Endpoint /exec/{id}/start ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the exec instance. #### Request Body - **StartExecOptions** - Required - Options for starting the exec instance. - **Detach** (bool) - Optional - Whether to detach from the command after starting. - **Tty** (bool) - Optional - Whether to allocate a pseudo-TTY. ### Request Example ```json { "Detach": false, "Tty": false } ``` ### Response #### Success Response (200 OK) - **()** - Indicates successful start. If Tty is true, the response will be a stream. #### Response Example (Response content depends on Tty and Detach options) ``` -------------------------------- ### StartExecOptions Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Options for starting an exec instance. ```APIDOC ## StartExecOptions ### Description Options to configure the starting of an already created exec instance. ### Fields - **detach** (bool) - Whether to detach the exec process after starting. - **tty** (bool) - Whether to allocate a pseudo-TTY for the exec process. ### Example ```rust use dockworker::options::StartExecOptions; let mut options = StartExecOptions::new(); options.detach(true); options.tty(true); ``` ``` -------------------------------- ### start_container Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts a specified container. ```APIDOC ## start_container ### Description Starts a Docker container. ### API POST /containers/{id}/start ### Parameters #### Path Parameters * `id` (string) - The ID or name of the container to start. ### Returns * `Result<(), DwError>` - An empty result on success, or a DwError on failure. ``` -------------------------------- ### Start Container Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Starts a specified container using its ID. ```rust pub async fn start_container(&self, id: &str) -> Result<(), DwError> ``` -------------------------------- ### Exec Start Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts an exec instance in a container. This method allows for streaming of attach response frames. ```APIDOC ## POST /exec/{id}/start ### Description Starts an exec instance in a container and returns a stream of attach response frames. ### Method POST ### Endpoint /exec/{id}/start ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the exec instance to start. #### Request Body - **option** (AttachOption) - Required - Options for starting the exec instance. ### Request Example ```json { "example": "{\"Detach\": false, \"Tty\": false}" } ``` ### Response #### Success Response (200 OK) - **AttachResponseFrame** (stream) - A stream of frames representing the attach response. #### Response Example ```json { "example": "[AttachResponseFrame data]" } ``` ``` -------------------------------- ### StartExecOptions Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.StartExecOptions.html Represents the configuration options for starting an exec instance. This struct is used as the request body for the /exec/start endpoint. ```APIDOC ## Struct StartExecOptions ### Description request body of /exec/start an exec instance ### Methods #### `new()` Creates a new instance of `StartExecOptions`. #### `detach(detach: bool)` Sets the detach option for the exec instance. #### `tty(tty: bool)` Sets the TTY option for the exec instance. ``` -------------------------------- ### StartExecOptions Summary Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.StartExecOptions.html Defines the structure for exec start options. This struct is internal and its fields are not directly accessible. ```rust pub struct StartExecOptions { /* private fields */ } ``` -------------------------------- ### Start Exec Instance Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Starts a previously created exec instance within a container. If detach is true, it returns immediately; otherwise, it establishes an interactive session. ```rust pub async fn start_exec( &self, id: &str, option: &StartExecOptions, ) -> Result>, DwError> ``` -------------------------------- ### Start and Wait for Container Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts a container and then waits for it to exit. This is a common pattern for running short-lived tasks. ```rust async fn stop_wait_container(docker: &Docker, container: &str) { docker.start_container(container).await.unwrap(); docker.wait_container(container).await.unwrap(); } ``` -------------------------------- ### Start Container with Checkpoint Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Starts a Docker container, optionally specifying a checkpoint and checkpoint directory. Uses URL-encoded parameters for the request. ```rust pub async fn start_container( &self, id: &str, checkpoint_id: &str, checkpoint_dir: Option<&str>, ) -> Result<(), DwError> { let mut param = url::form_urlencoded::Serializer::new(String::new()); param.append_pair("checkpoint", &checkpoint_id); if let Some(dir) = checkpoint_dir { param.append_pair("checkpoint-dir", &dir); } self.http_client() .post( self.headers(), &format!("/containers/{}/start?{{}}", id, param.finish()), "", ) .await?; no_content(res).map_err(Into::into) } ``` -------------------------------- ### Implement GET Request with HyperClient Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Handles GET requests, including following redirects and fetching the response body. ```rust async fn get(&self, headers: &HeaderMap, path: &str) -> Result>, Self::Err> { let url = join_uri(&self.base, path)?; let res = request_with_redirect::>( self.client.clone(), http::Method::GET, url, headers.clone(), None, ) .await?; let res = fetch_body(res).await?; Ok(res) } ``` -------------------------------- ### Connect to Docker and Get Version Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Connects to the Docker daemon using default settings and retrieves the Docker version. Ensure Docker is running. ```rust async fn test_version() { let docker = Docker::connect_with_defaults().unwrap(); docker.version().await.unwrap(); } ``` -------------------------------- ### Making an HTTP Request with Hyper Client Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Example of constructing and sending an HTTP request using the Hyper client. This snippet demonstrates sending a request with a body and handling the response. ```rust impl HyperClient { pub async fn post_json(&self, url: &str, body: Option) -> Result { let mut headers = HeaderMap::new(); headers.insert(CONTENT_TYPE, "application/json".parse().unwrap()); let res = self.client.request( hyper::Method::POST, url, headers.clone(), Some(buf), ) .await?; let res = fetch_body(res).await?; Ok(res) } } ``` -------------------------------- ### Example of IPAMConfig AuxiliaryAddresses Source: https://docs.rs/dockworker/0.16.0/dockworker/network/struct.IPAMConfig.html Illustrates how the AuxiliaryAddresses field in IPAMConfig is populated based on a docker network create command with --aux-address. ```bash docker network create -d macvlan .. --aux-address="my-router=172.16.86.1" .. ``` ```rust HashMap::from([("my-router", "172.16.86.5")]) ``` -------------------------------- ### Upload File to Container Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Uploads a file to a container. This example first creates a temporary file, archives it, uploads it, and then verifies its presence. ```rust async fn put_file_container(docker: &Docker, container: &str) { let temp_dir = env::temp_dir(); let test_file = temp_dir.join("test_file"); gen_rand_file(&test_file, 1024).await.unwrap(); // prepare test file tokio::task::spawn_blocking({ let test_file = test_file.clone(); move || { let file = std::fs::File::create(test_file.with_extension("tar")).unwrap(); let mut builder = tar::Builder::new(file); let mut file2 = std::fs::File::open(&test_file).unwrap(); builder .append_file(test_file.strip_prefix("/").unwrap(), &mut file2) .unwrap(); } }) .await .unwrap(); let res = docker.get_file(container, &test_file).await; assert!(matches!( res.map(|_| ()).unwrap_err(), DwError::Docker(_) // not found )); docker .put_file( container, &test_file.with_extension("tar"), Path::new("/"), true, ) .await .unwrap(); let src = docker.get_file(container, &test_file).await.unwrap(); let buf = read_bytes_stream_to_end(src).await; let temp_dir_put = temp_dir.join("put"); tokio::task::spawn_blocking(move || { let cur = std::io::Cursor::new(buf); tar::Archive::new(cur).unpack(&temp_dir_put).unwrap(); }) .await .unwrap(); docker.wait_container(container).await.unwrap(); let is_eq = equal_file( ``` -------------------------------- ### Get Docker System Information Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Retrieves general system information from the Docker daemon. ```rust pub async fn system_info(&self) -> Result { let res = self.http_client().get(self.headers(), "/info").await?; api_result(res).map_err(Into::into) } ``` -------------------------------- ### Version Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Retrieves version and various information about the Docker server. It sends a GET request to the /version endpoint. ```APIDOC ## GET /version ### Description Get version and various information. ### Method GET ### Endpoint /version ### Response #### Success Response (200) - **body** (Version) - Information about the Docker version and system. ``` -------------------------------- ### Default ContainerListOptions Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.ContainerListOptions.html Returns the default ContainerListOptions. This is useful for starting with a base configuration before applying specific options. ```rust fn default() -> ContainerListOptions ``` -------------------------------- ### Get Container Stats Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Shows how to retrieve resource usage statistics for a running container. Useful for monitoring. ```rust { let create = ContainerCreateOptions::new(image); let container = docker .create_container(Some(&next_id()), &create) .await .unwrap(); stats_container(docker, &container.id).await; docker .remove_container(&container.id, None, None, None) .await .unwrap(); } ``` -------------------------------- ### Get System Information Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Retrieves comprehensive information about the Docker system, including version, storage drivers, and configured plugins. ```APIDOC ## GET /info ### Description Get system information. ### Method GET ### Endpoint /info ``` -------------------------------- ### Set Healthcheck Start Interval Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.HealthcheckConfig.html Sets the interval between health checks specifically during the start period. The provided Duration is converted to nanoseconds. A value of 0 inherits the start interval from the image. ```rust pub fn start_interval(&mut self, start_interval: Duration) -> &mut Self ``` -------------------------------- ### Initialize Docker Client Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Creates a new `Docker` instance with the provided HTTP client and protocol. Initializes headers and sets credentials to `None`. ```rust fn new(client: HyperClient, protocol: Protocol) -> Self { Self { client, protocol, headers: HeaderMap::new(), credential: std::sync::Arc::new(std::sync::Mutex::new(None)), } } ``` -------------------------------- ### NetworkCreateOptions::new Source: https://docs.rs/dockworker/0.16.0/src/dockworker/network.rs.html Initializes NetworkCreateOptions with default values for creating a network. Equivalent to `docker network create `. ```rust pub fn new(name: &str) -> Self { Self { attachable: false, check_duplicate: true, driver: "bridge".to_owned(), enable_ipv6: false, ipam: IPAM::default(), ingress: false, internal: false, labels: HashMap::new(), name: name.to_owned(), options: HashMap::new(), } } ``` -------------------------------- ### Create Network with Default Bridge Options Source: https://docs.rs/dockworker/0.16.0/dockworker/network/struct.NetworkCreateOptions.html Demonstrates how to create a network equivalent to the default bridge network using NetworkCreateOptions and its builder methods. ```rust let network_name = "sample-network"; let mut opt = NetworkCreateOptions::new(network_name); opt.enable_icc() .enable_ip_masquerade() .host_binding_ipv4(Ipv4Addr::new(0, 0, 0, 0)) .bridge_name("docker0") .driver_mtu(1500); // let network = docker.create_network(&opt)?; ``` -------------------------------- ### Implement GET Stream Request with HyperClient Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Handles GET requests that return a streaming response body. ```rust async fn get_stream( &self, headers: &HeaderMap, path: &str, ) -> Result, Self::Err> { let url = join_uri(&self.base, path)?; let res = request_with_redirect::>( self.client.clone(), http::Method::GET, url, headers.clone(), None, ) .await?; Ok(res) } ``` -------------------------------- ### CreateExecOptions Builder Pattern Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Demonstrates the builder pattern for constructing `CreateExecOptions`. Use this to configure parameters like TTY, environment variables, and commands for executing commands within a container. ```rust impl CreateExecOptions { pub fn new() -> Self { Self { attach_stdin: false, attach_stdout: true, attach_stderr: true, detach_keys: "".to_owned(), tty: false, env: vec![], cmd: vec![], privileged: false, user: "".to_owned(), working_dir: PathBuf::new(), } } pub fn attach_stdin(&mut self, attach_stdin: bool) -> &mut Self { self.attach_stdin = attach_stdin; self } pub fn attach_stdout(&mut self, attach_stdout: bool) -> &mut Self { self.attach_stdout = attach_stdout; self } pub fn attach_stderr(&mut self, attach_stderr: bool) -> &mut Self { self.attach_stderr = attach_stderr; self } pub fn tty(&mut self, tty: bool) -> &mut Self { self.tty = tty; self } pub fn env(&mut self, env: String) -> &mut Self { self.env.push(env); self } /// push back a cmd argment pub fn cmd(&mut self, cmd: String) -> &mut Self { self.cmd.push(cmd); self } pub fn privileged(&mut self, privileged: bool) -> &mut Self { self.privileged = privileged; self } pub fn user(&mut self, user: String) -> &mut Self { self.user = user; self } pub fn working_dir(&mut self, working_dir: PathBuf) -> &mut Self { self.working_dir = working_dir; self } } ``` -------------------------------- ### GET Stream Request Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Performs an HTTP GET request and returns the response body as a hyper::Body stream. ```APIDOC ## GET Stream ### Description Performs an HTTP GET request and returns the response body as a stream. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (string) - Required - The path to the resource. #### Headers - **headers** (HeaderMap) - Required - The HTTP headers to include in the request. ### Response #### Success Response (200) - **Response** - The response from the server, with the body as a hyper::Body stream. ``` -------------------------------- ### NetworkCreateOptions::new Source: https://docs.rs/dockworker/0.16.0/dockworker/network/struct.NetworkCreateOptions.html Initializes NetworkCreateOptions with a given name, equivalent to `docker network create `. ```rust pub fn new(name: &str) -> Self ``` -------------------------------- ### Create New Container Options Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Initializes a new container configuration with a specified Docker image. Sets default values for most options. ```rust pub fn new(image: &str) -> Self { Self { hostname: "".to_owned(), domainname: "".to_owned(), user: "".to_owned(), attach_stdin: false, attach_stdout: true, attach_stderr: true, tty: false, open_stdin: false, stdin_once: false, env: vec![], cmd: vec![], image: image.to_owned(), working_dir: PathBuf::new(), entrypoint: vec![], network_disabled: false, mac_address: "".to_owned(), on_build: vec![], labels: HashMap::new(), stop_signal: "SIGTERM".to_owned(), stop_timeout: Duration::from_secs(10), host_config: None, networking_config: None, exposed_ports: None, healthcheck: None, } } ``` -------------------------------- ### GET Request Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Performs an HTTP GET request to the specified path with given headers. Returns the response body as a byte vector. ```APIDOC ## GET ### Description Performs an HTTP GET request. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (string) - Required - The path to the resource. #### Headers - **headers** (HeaderMap) - Required - The HTTP headers to include in the request. ### Response #### Success Response (200) - **Response>** - The response from the server, with the body as a byte vector. ``` -------------------------------- ### StartExecOptions Builder Pattern Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Provides a builder pattern for configuring `StartExecOptions`. Use this to specify whether to detach the execution and whether to allocate a TTY. ```rust impl StartExecOptions { pub fn new() -> Self { Self { detach: false, tty: false, } } pub fn detach(&mut self, detach: bool) -> &mut Self { self.detach = detach; self } pub fn tty(&mut self, tty: bool) -> &mut Self { self.tty = tty; self } } ``` -------------------------------- ### Get Minimum of Two ExitStatus Instances Source: https://docs.rs/dockworker/0.16.0/dockworker/container/struct.ExitStatus.html Provides a method to get the minimum of two ExitStatus values. This is part of the Ord trait implementation. ```rust fn min(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### DeviceMapping::new Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.DeviceMapping.html Constructs a new DeviceMapping instance. ```APIDOC ## pub fn new( path_on_host: PathBuf, path_in_container: PathBuf, cgroup_permissions: String, ) -> Self ### Description Constructs a new DeviceMapping instance. ### Parameters * **path_on_host** (PathBuf) - The path of the device on the host system. * **path_in_container** (PathBuf) - The path of the device within the container. * **cgroup_permissions** (String) - The cgroup permissions for the device. ### Returns A new DeviceMapping instance. ``` -------------------------------- ### Get Maximum of Two ExitStatus Instances Source: https://docs.rs/dockworker/0.16.0/dockworker/container/struct.ExitStatus.html Provides a method to get the maximum of two ExitStatus values. This is part of the Ord trait implementation. ```rust fn max(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Get Value from HashMap Source: https://docs.rs/dockworker/0.16.0/dockworker/container/type.UnspecifiedObject.html Use `get` to retrieve an immutable reference to the value associated with a key. The key can be a borrowed form of the map's key type, provided it implements `Hash` and `Eq`. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### DeviceMapping::new Constructor Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.DeviceMapping.html Creates a new DeviceMapping instance. Requires the path of the device on the host, its path inside the container, and the cgroup permissions. ```rust pub fn new( path_on_host: PathBuf, path_in_container: PathBuf, cgroup_permissions: String, ) -> Self ``` -------------------------------- ### Set Healthcheck Start Period Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.HealthcheckConfig.html Configures the initial period during which health checks are not considered failures, allowing the container to initialize. The provided Duration is converted to nanoseconds. A value of 0 inherits the start period from the image. ```rust pub fn start_period(&mut self, start_period: Duration) -> &mut Self ``` -------------------------------- ### NetworkCreateOptions::new Source: https://docs.rs/dockworker/0.16.0/src/dockworker/network.rs.html Initializes a new NetworkCreateOptions struct with default settings for creating a bridge network. ```APIDOC ## NetworkCreateOptions::new ### Description Initializes a new `NetworkCreateOptions` struct with default settings, suitable for creating a bridge network. ### Method Signature `pub fn new(name: &str) -> Self` ### Parameters - **name** (string) - The name of the network to be created. ``` -------------------------------- ### Deserialize Implementation Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.PortBindings.html Allows PortBindings to be deserialized, for example, when receiving configuration data. ```APIDOC ### impl<'de> Deserialize<'de> for PortBindings #### fn deserialize>(deserializer: D) -> Result Deserializes the `PortBindings` value from the given Serde deserializer. ``` -------------------------------- ### I/O Options Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Configure I/O related settings for the container. ```APIDOC ## I/O Options ### `io_maximum_bandwidth` Maximum IOPS (Input/Output Operations Per Second) for the container. This is a rate limit. ### `io_maximum_ops` Maximum IOPS (Input/Output Operations Per Second) for the container. This is a rate limit. ### `blkio_weight` Block I/O weight (relative weight). Default is 500. Higher values give more I/O bandwidth to the container. ``` -------------------------------- ### Serialize Implementation Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.PortBindings.html Allows PortBindings to be serialized, for example, when sending configuration data. ```APIDOC ### impl Serialize for PortBindings #### fn serialize(&self, serializer: S) -> Result Serializes the `PortBindings` value into the given Serde serializer. ``` -------------------------------- ### Get Container Processes Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Lists the processes running inside a specified container. ```rust pub async fn container_top(&self, container_id: &str) -> Result ``` -------------------------------- ### Container Lifecycle and Configuration Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Configure container lifecycle and general configuration settings. ```APIDOC ## Container Lifecycle and Configuration ### `publish_all_ports` Publish all exposed ports to the host. If `true`, all ports defined in the Dockerfile's EXPOSE instruction will be published. ### `auto_remove` Automatically remove the container when it exits. ### `group_add` List of additional groups to add the container process to. ### `restart_policy` Restart policy for the container. Examples: `no`, `on-failure`, `always`, `unless-stopped`. ### `sysctls` Set of kernel parameters to set in the container. Example: `{"net.core.somaxconn": "511"}`. ### `runtime` Runtime to use for the container. Example: `nvidia`. ``` -------------------------------- ### Get Container Information Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Retrieves detailed information about a specific container, identified by its ID. ```APIDOC ## GET /containers/{id}/json ### Description Inspect about a container. ### Method GET ### Endpoint /containers/{id}/json ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container to inspect. ``` -------------------------------- ### List Containers with Filters Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Shows how to list containers, applying filters to narrow down the results. Useful for finding specific containers. ```rust let mut filter = ContainerFilters::new(); filter.name("test_container_"); let containers = docker .list_containers(Some(true), None, Some(true), filter.clone()) .await .unwrap(); assert!( containers.is_empty(), "remove containers 'test_container_*'" ); ``` -------------------------------- ### Get Container Processes List Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Retrieves a list of processes running within a container. ```rust pub async fn processes( &self, container_id: &str, ) -> Result, DwError> ``` -------------------------------- ### Any::type_id() - Blanket Implementation Source: https://docs.rs/dockworker/0.16.0/dockworker/image/struct.ImageFilters.html Gets the TypeId of the ImageFilters type. This is a blanket implementation for the Any trait. ```rust fn type_id(&self) -> TypeId> ``` -------------------------------- ### CreateExecOptions Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Options for creating an exec instance within a container. ```APIDOC ## CreateExecOptions ### Description Options to configure the creation of an exec instance, which allows running commands inside a running container. ### Fields - **attach_stdin** (bool) - Whether to attach to the standard input of the exec process. - **attach_stdout** (bool) - Whether to attach to the standard output of the exec process. - **attach_stderr** (bool) - Whether to attach to the standard error of the exec process. - **detach_keys** (String) - The keys sequence to use for detaching the exec process. - **tty** (bool) - Whether to allocate a pseudo-TTY for the exec process. - **env** (Vec) - A list of environment variables to set for the exec process. - **cmd** (Vec) - The command and arguments to run as the exec process. - **privileged** (bool) - Whether to run the exec process in privileged mode. - **user** (String) - The user to run the exec process as. - **working_dir** (PathBuf) - The working directory for the exec process. ### Example ```rust use dockworker::options::CreateExecOptions; let mut options = CreateExecOptions::new(); options.cmd(String::from("ls")); options.cmd(String::from("-l")); options.user(String::from("root")); ``` ``` -------------------------------- ### Container Operations Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Methods for managing containers, including listing, creating, starting, stopping, and removing them. ```APIDOC ## list_containers(all: Option, limit: Option, size: Option, filters: ContainerFilters) ### Description List containers. ### Method `pub async fn list_containers( &self, all: Option, limit: Option, size: Option, filters: ContainerFilters, ) -> Result, DwError>` ### API `/containers/json` ### Parameters #### Query Parameters - **all** (boolean) - Optional - If true, show all containers. - **limit** (u64) - Optional - Maximum number of containers to return. - **size** (boolean) - Optional - If true, return the size of containers. - **filters** (ContainerFilters) - Required - Filters to apply to the list of containers. ### Response Example ```json { "example": "[Container object, ...]" } ``` ## create_container(name: Option<&str>, option: &ContainerCreateOptions) ### Description Create a container. ### Method `pub async fn create_container( &self, name: Option<&str>, option: &ContainerCreateOptions, ) -> Result` ### API `POST /containers/create?{name}` ### Parameters #### Query Parameters - **name** (string) - Optional - Name for the container. If not provided, Docker will auto-name it. #### Request Body - **option** (ContainerCreateOptions) - Required - Options for creating the container. ### Response Example ```json { "example": "CreateContainerResponse object" } ``` ## start_container(id: &str) ### Description Start a container. ### Method `pub async fn start_container(&self, id: &str) -> Result<(), DwError>` ### API `/containers/{id}/start` ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container to start. ### Response Example ```json { "example": "Success or DwError" } ``` ## stop_container(id: &str, timeout: Duration) ### Description Stop a container. ### Method `pub async fn stop_container( &self, id: &str, timeout: Duration, ) -> Result<(), DwError>` ### API `/containers/{id}/stop` ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container to stop. #### Query Parameters - **timeout** (Duration) - Required - The time to wait before killing the container. ### Response Example ```json { "example": "Success or DwError" } ``` ## kill_container(id: &str, signal: Signal) ### Description Kill a container. ### Method `pub async fn kill_container( &self, id: &str, signal: Signal, ) -> Result<(), DwError>` ### API `/containers/{id}/kill` ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container to kill. #### Query Parameters - **signal** (Signal) - Required - The signal to send to the container. ### Response Example ```json { "example": "Success or DwError" } ``` ## rename_container(id: &str, name: &str) ### Description Rename a container specified with `id` to `name`. ### Method `pub async fn rename_container( &self, id: &str, name: &str, ) -> Result<(), DwError>` ### API `/containers/{id}/rename` ### Parameters #### Path Parameters - **id** (string) - Required - ID or name of the container. - **name** (string) - Required - New name for the container. ### Response Example ```json { "example": "Success or DwError" } ``` ## restart_container(id: &str, timeout: Duration) ### Description Restart a container. ### Method `pub async fn restart_container( &self, id: &str, timeout: Duration, ) -> Result<(), DwError>` ### API `/containers/{id}/restart` ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container to restart. #### Query Parameters - **timeout** (Duration) - Required - The time to wait before killing the container. ### Response Example ```json { "example": "Success or DwError" } ``` ## remove_container(id: &str, volume: Option, force: Option, link: Option) ### Description Remove a container. ### Method `pub async fn remove_container( &self, id: &str, volume: Option, force: Option, link: Option, ) -> Result<(), DwError>` ### API `/containers/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container to remove. #### Query Parameters - **volume** (boolean) - Optional - Whether to remove volumes associated with the container. - **force** (boolean) - Optional - Whether to force the removal of the container. - **link** (boolean) - Optional - Whether to remove linked container. ### Response Example ```json { "example": "Success or DwError" } ``` ``` -------------------------------- ### take Source: https://docs.rs/dockworker/0.16.0/dockworker/signal/struct.SignalIterator.html Creates an iterator that yields a specified number of elements from the beginning. ```APIDOC ## take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters - `n`: The maximum number of elements to yield. ``` -------------------------------- ### Cloning StartExecOptions Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.StartExecOptions.html Returns a duplicate of the StartExecOptions value. ```rust fn clone(&self) -> StartExecOptions ``` -------------------------------- ### CreateExecOptions Builder Methods Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.CreateExecOptions.html Provides builder-style methods to configure the options for creating an exec instance. Each method returns a mutable reference to self, allowing for chaining. ```rust pub fn new() -> Self ``` ```rust pub fn attach_stdin(&mut self, attach_stdin: bool) -> &mut Self ``` ```rust pub fn attach_stdout(&mut self, attach_stdout: bool) -> &mut Self ``` ```rust pub fn attach_stderr(&mut self, attach_stderr: bool) -> &mut Self ``` ```rust pub fn tty(&mut self, tty: bool) -> &mut Self ``` ```rust pub fn env(&mut self, env: String) -> &mut Self ``` ```rust pub fn cmd(&mut self, cmd: String) -> &mut Self ``` ```rust pub fn privileged(&mut self, privileged: bool) -> &mut Self ``` ```rust pub fn user(&mut self, user: String) -> &mut Self ``` ```rust pub fn working_dir(&mut self, working_dir: PathBuf) -> &mut Self ``` -------------------------------- ### Get Container Statistics Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Retrieves container statistics, both as a single snapshot and as a stream. Ensure the container is running. ```rust async fn stats_container(docker: &Docker, container: &str) { docker.start_container(container).await.unwrap(); // one shot let one_stats = docker .stats(container, Some(false), Some(true)) .await .unwrap(); use futures::StreamExt; let one_stats = one_stats.collect::>().await; assert_eq!(one_stats.len(), 1); // stream let thr_stats = docker .stats(container, Some(true), Some(false)) .await .unwrap() .take(3) .collect::>() .await; assert!(thr_stats.iter().all(Result::is_ok)); docker .stop_container(container, Duration::from_secs(10)) .await .unwrap(); } ``` -------------------------------- ### Create Exec Instance Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Runs a command inside a running container. ```APIDOC ## POST /containers/{id}/exec ### Description Run a command inside a running container. ### Method POST ### Endpoint /containers/{id}/exec ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. #### Request Body - **CreateExecOptions** - Required - Options for creating the exec instance. - **AttachStdin** (bool) - Optional - whether to attach the standard input, makes the command interactive. - **AttachStdout** (bool) - Optional - whether to attach the standard output. - **AttachStderr** (bool) - Optional - whether to attach the standard error. - **DetachKeys** (string) - Optional - Override the key sequence for detaching a container. - **Tty** (bool) - Optional - Allocate a pseudo-TTY. - **Cmd** (array of strings) - Required - The command to run. - **Env** (array of strings) - Optional - Environment variables to set. - **WorkingDir** (string) - Optional - Working directory inside the container. ### Request Example ```json { "Cmd": ["sh", "-c", "echo hello"], "AttachStdout": true, "AttachStderr": true } ``` ### Response #### Success Response (200 OK) - **CreateExecResponse** - Response containing the exec instance ID. - **Id** (string) - The ID of the created exec instance. #### Response Example ```json { "Id": "exec_instance_id" } ``` ``` -------------------------------- ### CPU Options Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Configure CPU-related settings for the container. ```APIDOC ## CPU Options ### `cpu_percent` CPU usage limit as a percentage. For example, `100` means one full CPU core. ### `cpu_shares` CPU shares (relative weight). Default is 1024. Higher values give more CPU time to the container. ### `cpu_period` CPU CFS (Completely Fair Scheduler) scheduling period in microseconds. Default is 100000. ### `cpu_quota` CPU CFS quota. The maximum amount of CPU time allowed in a given period. For example, `200000` means 2 CPUs worth of time if `cpu_period` is `100000`. ### `cpuset_cpus` CPU(s) allowed to run on. Example: `0-3` or `0,1`. ``` -------------------------------- ### Get information about files in a container Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Retrieves information about a file or directory within a container, including its stats. ```APIDOC ## HEAD /containers/{id}/archive ### Description Gets information about files in a container. ### Method HEAD ### Endpoint /containers/{id}/archive ### Parameters #### Path Parameters - **id** (string) - Required - The ID or name of the container. #### Query Parameters - **path** (string) - Required - The path to the resource in the container. ``` -------------------------------- ### Connect with SSL using OpenSSL Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Establishes an HTTPS connection using the OpenSSL backend. Requires private key, certificate, and CA certificate files. Ensures compatibility with docker-machine-esque addresses. ```rust pub fn connect_with_ssl( addr: &str, key: &Path, cert: &Path, ca: &Path, ) -> Result { let key_buf = std::fs::read(key)?; let cert_buf = std::fs::read(cert)?; let ca_buf = std::fs::read(ca)?; let pkey = openssl::pkey::PKey::from_rsa(openssl::rsa::Rsa::private_key_from_pem(&key_buf)?)?; let cert = openssl::x509::X509::from_pem(&cert_buf)?; let pkcs12 = openssl::pkcs12::Pkcs12::builder().build("", "", &pkey, &cert)?; let der = pkcs12.to_der()?; let id = native_tls::Identity::from_pkcs12(&der, "")?; let ca = native_tls::Certificate::from_pem(&ca_buf)?; let mut builder = native_tls::TlsConnector::builder(); builder.identity(id); builder.add_root_certificate(ca); // This ensures that using docker-machine-esque addresses work with Hyper. let addr_https = addr.to_string().replacen("tcp://", "https://", 1); let url = Uri::from_str(&addr_https).map_err(|err| DwError::InvalidUri { var: addr_https, source: err, })?; let mut http = hyper::client::HttpConnector::new(); http.enforce_http(false); let https = hyper_tls::HttpsConnector::from((http, builder.build()?.into())); let client = hyper::Client::builder().build::<_, hyper::Body>(https); Ok(Self::new(Client::HttpsClient(client), url)) } ``` -------------------------------- ### Get Docker Client Headers Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Returns a reference to the `HeaderMap` used for requests made by the Docker client. ```rust fn headers(&self) -> &HeaderMap { &self.headers } ``` -------------------------------- ### ContainerHostConfig Builder Methods Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Provides builder-style methods for configuring ContainerHostConfig options. ```rust impl ContainerHostConfig { pub fn new() -> Self { Self { ..Default::default() } } pub fn device_cgroup_rules(&mut self, device_cgroup_rules: Vec) -> &mut Self { self.device_cgroup_rules = Some(device_cgroup_rules); self } pub fn userns_mode(&mut self, userns_mode: String) -> &mut Self { self.userns_mode = Some(userns_mode); self } pub fn binds(&mut self, binds: Vec) -> &mut Self { self.binds = Some(binds); self } pub fn tmpfs(&mut self, tmpfs: HashMap) -> &mut Self { self.tmpfs = Some(tmpfs); self } pub fn links(&mut self, links: Vec) -> &mut Self { self.links = Some(links); self } pub fn memory(&mut self, memory: u64) -> &mut Self { self.memory = Some(memory); self } pub fn memory_swap(&mut self, memory_swap: u64) -> &mut Self { self.memory_swap = Some(memory_swap); self } ``` -------------------------------- ### Get the ImageId string Source: https://docs.rs/dockworker/0.16.0/dockworker/image/struct.ImageId.html Retrieves the string representation of the ImageId. This is useful for displaying or using the ID in other operations. ```rust pub fn id(&self) -> &str ``` -------------------------------- ### Process and Security Options Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Configure process and security-related settings for the container. ```APIDOC ## Process and Security Options ### `oom_kill_disable` Whether to disable the OOM (Out Of Memory) killer for the container. ### `oom_score_adj` Adjust the score used by the OOM killer. A higher score means the process is more likely to be killed. ### `pid_mode` PID (Process ID) mode for the container. Can be `private`, `host`, etc. ### `pids_limit` Maximum number of processes that can be created in the container. ### `privileged` Give extended privileges to the container. Use with caution. ### `readonly_rootfs` Mount the container's root filesystem as read-only. ### `cap_add` Add Linux capabilities to the container. Example: `NET_ADMIN`. ### `cap_drop` Drop Linux capabilities from the container. Example: `MKNOD`. ### `security_opt` Security options for the container. Example: `seccomp=unconfined`. ``` -------------------------------- ### Get Token String Source: https://docs.rs/dockworker/0.16.0/dockworker/credentials/struct.IdentityToken.html Retrieves the string representation of the IdentityToken. This is the actual token value used for authentication. ```rust pub fn token(&self) -> String ``` -------------------------------- ### Connect with HTTP Source: https://docs.rs/dockworker/0.16.0/src/dockworker/hyper_client.rs.html Establishes a standard HTTP connection. Adapts docker-machine-esque addresses to use 'http://' scheme. ```rust pub fn connect_with_http(addr: &str) -> Result { // This ensures that using docker-machine-esque addresses work with Hyper. let addr_https = addr.to_string().replace("tcp://", "http://"); let url = Uri::from_str(&addr_https).map_err(|err| DwError::InvalidUri { var: addr_https, source: err, })?; Ok(Self::new(Client::HttpClient(hyper::Client::new()), url)) } ``` -------------------------------- ### Set On Build Instructions Source: https://docs.rs/dockworker/0.16.0/src/dockworker/options.rs.html Sets the 'on build' instructions for an automated build. Overwrites any existing instructions. ```rust pub fn on_build(&mut self, on_build: Vec) -> &mut Self { self.on_build = on_build; self } ``` -------------------------------- ### Ping Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Checks if the Docker server is accessible. It sends a GET request to the /_ping endpoint and expects an 'OK' response. ```APIDOC ## GET /_ping ### Description Test if the server is accessible. ### Method GET ### Endpoint /_ping ### Response #### Success Response (200) - **body** (string) - Should be 'OK' #### Response Example ``` OK ``` ``` -------------------------------- ### Get a tarball containing all images and metadata for a repository Source: https://docs.rs/dockworker/0.16.0/src/dockworker/docker.rs.html Exports a specified image as a tarball, including all its layers and metadata. ```APIDOC ## GET /images/{name}/get ### Description Exports a specified image as a tarball, including all its layers and metadata. ### Method GET ### Endpoint /images/{name}/get ### Parameters #### Path Parameters - **name** (string) - Required - The name or ID of the image to export. ### Response #### Success Response (200) - **(Stream of Bytes)** - The tarball content of the image. #### Response Example (Binary stream of tarball content) ``` -------------------------------- ### Initialize ContainerCreateOptions Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.ContainerCreateOptions.html Creates a new instance of ContainerCreateOptions, requiring the image name as a mandatory argument. ```rust pub fn new(image: &str) -> Self ``` -------------------------------- ### Get Container Stats Source: https://docs.rs/dockworker/0.16.0/dockworker/struct.Docker.html Fetches resource usage statistics for a container. Supports streaming and one-shot retrieval of stats. ```rust pub async fn stats( &self, container_id: &str, stream: Option, oneshot: Option, ) -> Result>, DwError> ```