-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.rs
More file actions
285 lines (265 loc) · 8.22 KB
/
client.rs
File metadata and controls
285 lines (265 loc) · 8.22 KB
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
//! Docker CLI client implementation
use std::path::Path;
use super::error::DockerError;
use crate::shared::command::CommandExecutor;
/// Client for executing Docker CLI commands
///
/// This client wraps Docker CLI operations using our `CommandExecutor` collaborator,
/// enabling testability and consistency with other external tool clients (Ansible,
/// `OpenTofu`, LXD). Each Docker subcommand is exposed as a separate method.
///
/// # Architecture
///
/// The client uses `CommandExecutor` as a collaborator for actual command execution,
/// following the same pattern as `AnsibleClient`, `TofuClient`, and `LxdClient`.
///
/// # Example
///
/// ```rust,no_run
/// use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let docker = DockerClient::new();
///
/// // Build an image
/// docker.build_image("docker/app", "my-app", "latest")?;
///
/// // Check if it exists
/// let exists = docker.image_exists("my-app", "latest")?;
/// assert!(exists);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DockerClient {
command_executor: CommandExecutor,
}
impl Default for DockerClient {
fn default() -> Self {
Self::new()
}
}
impl DockerClient {
/// Create a new Docker client
///
/// # Example
///
/// ```rust
/// use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
///
/// let docker = DockerClient::new();
/// ```
#[must_use]
pub fn new() -> Self {
Self {
command_executor: CommandExecutor::new(),
}
}
/// Build a Docker image from a Dockerfile directory
///
/// Executes `docker build -t <name>:<tag> <path>` to build an image.
///
/// # Arguments
///
/// * `dockerfile_dir` - Path to directory containing the Dockerfile
/// * `image_name` - Name for the Docker image (e.g., "my-ssh-server")
/// * `image_tag` - Tag for the image (e.g., "latest")
///
/// # Returns
///
/// The build output on success
///
/// # Errors
///
/// Returns `DockerError::BuildFailed` if the build command fails
///
/// # Example
///
/// ```rust,no_run
/// # use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let docker = DockerClient::new();
/// docker.build_image("docker/ssh-server", "my-ssh", "latest")?;
/// # Ok(())
/// # }
/// ```
pub fn build_image<P: AsRef<Path>>(
&self,
dockerfile_dir: P,
image_name: &str,
image_tag: &str,
) -> Result<String, DockerError> {
let image = format!("{image_name}:{image_tag}");
let path = dockerfile_dir.as_ref().display().to_string();
let args = vec!["build", "-t", &image, &path];
self.command_executor
.run_command("docker", &args, None)
.map(|result| result.stdout)
.map_err(|source| DockerError::BuildFailed { image, source })
}
/// List Docker images with optional repository filter
///
/// Executes `docker images` with formatting to get structured output.
///
/// # Arguments
///
/// * `repository` - Optional repository name to filter by
///
/// # Returns
///
/// A vector of image information strings in format:
/// "repository:tag|id|size"
///
/// # Errors
///
/// Returns `DockerError::ListImagesFailed` if the command fails
///
/// # Example
///
/// ```rust,no_run
/// # use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let docker = DockerClient::new();
/// // List all images
/// let all_images = docker.list_images(None)?;
///
/// // List specific repository
/// let ubuntu_images = docker.list_images(Some("ubuntu"))?;
/// # Ok(())
/// # }
/// ```
pub fn list_images(&self, repository: Option<&str>) -> Result<Vec<String>, DockerError> {
let format_str = "{{.Repository}}:{{.Tag}}|{{.ID}}|{{.Size}}";
let mut args = vec!["images", "--format", format_str];
if let Some(repo) = repository {
args.push(repo);
}
let result = self
.command_executor
.run_command("docker", &args, None)
.map_err(DockerError::ListImagesFailed)?;
Ok(result.stdout.lines().map(ToString::to_string).collect())
}
/// List Docker containers
///
/// Executes `docker ps` with formatting to get structured output.
///
/// # Arguments
///
/// * `all` - If true, shows all containers (including stopped ones)
///
/// # Returns
///
/// A vector of container information strings in format:
/// "id|name|status"
///
/// # Errors
///
/// Returns `DockerError::ListContainersFailed` if the command fails
///
/// # Example
///
/// ```rust,no_run
/// # use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let docker = DockerClient::new();
/// // List only running containers
/// let running = docker.list_containers(false)?;
///
/// // List all containers
/// let all_containers = docker.list_containers(true)?;
/// # Ok(())
/// # }
/// ```
pub fn list_containers(&self, all: bool) -> Result<Vec<String>, DockerError> {
let format_str = "{{.ID}}|{{.Names}}|{{.Status}}";
let mut args = vec!["ps", "--format", format_str];
if all {
args.push("-a");
}
let result = self
.command_executor
.run_command("docker", &args, None)
.map_err(DockerError::ListContainersFailed)?;
Ok(result.stdout.lines().map(ToString::to_string).collect())
}
/// Get logs from a Docker container
///
/// Executes `docker logs <container-id>` to retrieve container logs.
///
/// # Arguments
///
/// * `container_id` - ID or name of the container
///
/// # Returns
///
/// The container's logs as a string
///
/// # Errors
///
/// Returns `DockerError::GetLogsFailed` if the command fails
///
/// # Example
///
/// ```rust,no_run
/// # use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let docker = DockerClient::new();
/// let logs = docker.get_container_logs("my-container")?;
/// println!("Container logs:\n{}", logs);
/// # Ok(())
/// # }
/// ```
pub fn get_container_logs(&self, container_id: &str) -> Result<String, DockerError> {
let args = vec!["logs", container_id];
self.command_executor
.run_command("docker", &args, None)
.map(|result| result.stdout)
.map_err(|source| DockerError::GetLogsFailed {
container_id: container_id.to_string(),
source,
})
}
/// Check if a Docker image exists locally
///
/// Uses `list_images` to check for the presence of a specific image.
///
/// # Arguments
///
/// * `image_name` - Name of the image
/// * `image_tag` - Tag of the image
///
/// # Returns
///
/// `true` if the image exists, `false` otherwise
///
/// # Errors
///
/// Returns `DockerError::ListImagesFailed` if the command fails
///
/// # Example
///
/// ```rust,no_run
/// # use torrust_tracker_deployer_lib::adapters::docker::DockerClient;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let docker = DockerClient::new();
/// if docker.image_exists("ubuntu", "latest")? {
/// println!("Ubuntu image is available");
/// }
/// # Ok(())
/// # }
/// ```
pub fn image_exists(&self, image_name: &str, image_tag: &str) -> Result<bool, DockerError> {
let filter = format!("{image_name}:{image_tag}");
let images = self.list_images(Some(&filter))?;
Ok(!images.is_empty())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_create_docker_client() {
let _docker = DockerClient::new();
}
}