Skip to main content

shipshape/
lib.rs

1//! Shipshape
2//! 
3//! A library for interacting with the Docker API from Rust
4//! Meant to be as simple as possible
5
6use std::error::Error;
7
8use hyper::{body, Body, Method, Request};
9use hyper_socket::UnixSocketConnector;
10
11///Socet to connect to
12static DOCKERSOCKET : &'static str = "/var/run/docker.sock";
13
14///Make HTTP requests to Docker
15async fn make_http_request(endpoint: String, body_str: String) -> Result<String, Box<dyn Error + Send + Sync>> {
16	let socket = UnixSocketConnector::new(DOCKERSOCKET);
17	let client = hyper::Client::builder()
18		.build::<_, Body>(socket);
19
20	//Build request
21	let req = Request::builder()
22		.method(Method::POST)
23		.header("content-type", "application/json")
24		.uri(endpoint)
25		.body(Body::from(body_str))?;
26
27	let mut response_str: String = "".to_string();
28
29	//Send request
30	match client.request(req).await {
31		Ok(res) => {
32			let response_bytes = body::to_bytes(res.into_body()).await?;
33			response_str = String::from_utf8(response_bytes.to_vec()).expect("response was not valid utf-8");
34		}
35		Err(err) => eprintln!("shipshape Error: {}", err),
36	}
37
38	Ok(response_str)
39}
40
41
42///Create a docker container from an image
43///Must specify the full JSON encoded body to send to the API
44///See <https://docs.docker.com/engine/api/v1.41/#operation/ContainerCreate> for complete list of
45///valid options
46pub async fn create_container(body_str: String) -> Result<String, Box<dyn Error + Send + Sync>> {
47	make_http_request("http://localhost/containers/create".to_string(), body_str).await
48}
49
50///Start a docker container from container ID
51pub async fn start_container(container_id: String) -> Result<String, Box<dyn Error + Send + Sync>> {
52	make_http_request(format!("http://localhost/containers/{}/start", container_id), "".to_string()).await
53}
54
55///Stop a docker container from container ID
56pub async fn stop_container(container_id: String) -> Result<String, Box<dyn Error + Send + Sync>> {
57	make_http_request(format!("http://localhost/containers/{}/stop", container_id), "".to_string()).await
58}
59
60///Pause a docker container from container ID
61pub async fn pause_container(container_id: String) -> Result<String, Box<dyn Error + Send + Sync>> {
62	make_http_request(format!("http://localhost/containers/{}/pause", container_id), "".to_string()).await
63}
64
65
66///Unpause a docker container from container ID
67pub async fn unpause_container(container_id: String) -> Result<String, Box<dyn Error + Send + Sync>> {
68	make_http_request(format!("http://localhost/containers/{}/unpause", container_id), "".to_string()).await 
69}