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
use hyper::StatusCode;

use crate::client::container_files::DecContainerFiles;
use crate::client::shared::parse_container_log;
use crate::DockerEngineClient;
use crate::errors::DecUseError;
use crate::requests::{CreateExecRequest, InspectContainerArgs, LogsArgs, RemoveContainerArgs, WaitCondition};
use crate::responses::{CreateExecResponse, InspectContainerResponse, TopResponse, WaitResponse};
use crate::model::{StreamLine, TsStreamLine};

pub struct DecContainer<'a> {
    pub(super) client: &'a DockerEngineClient,
    pub(super) container_id: String
}

impl <'a> DecContainer<'a> {

    /// Create a command to run within a container, but don't start or execute the command.
    pub async fn create_exec(&self, request: CreateExecRequest) -> Result<CreateExecResponse, DecUseError> {
        let uri = self.client.url.containers().create_exec(&self.container_id);
        let response = self.client.http.post_json(uri, &request)?.execute().await?;

        response
            .assert_item_status(StatusCode::CREATED)?
            .parse()
    }

    /// Work with files inside a container.
    pub fn files(&'_ self) -> DecContainerFiles<'_> {
        DecContainerFiles {
            client: self.client,
            container_id: &self.container_id
        }
    }

    /// Get the console output (stdout and/or stderr) of a container.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///     let log = dec.container("example").logs().await?;
    ///
    ///     println!("Container log:");
    ///     for line in log {
    ///         println!("{}", line.text);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn logs(&self) -> Result<Vec<StreamLine>, DecUseError> {
        self.logs_with(LogsArgs::default()).await
    }

    pub async fn logs_timestamped(&self) -> Result<Vec<Result<TsStreamLine, String>>, DecUseError> {
        let lines = self.logs_with(LogsArgs::default().timestamps()).await?;

        let results = lines
            .iter()
            .map(TsStreamLine::try_from)
            .collect();

        Ok(results)
    }

    async fn logs_with(&self, args: LogsArgs) -> Result<Vec<StreamLine>, DecUseError> {
        let uri = self.client.url.containers().logs(&self.container_id, args)?;
        let response = self.client.http.get(uri)?.execute().await?;

        response
            .assert_item_status(StatusCode::OK)?
            .parse_with(parse_container_log)
    }

    /// Inspect a container.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///     let container = dec.container("example").inspect().await?;
    ///
    ///     println!("Container status: {}", container.state.status);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn inspect(&self) -> Result<InspectContainerResponse, DecUseError> {
        self.inspect_with(InspectContainerArgs::default()).await
    }

    /// Inspect a container, with additional request arguments.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::requests::InspectContainerArgs;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///     let container = dec.container("example")
    ///         .inspect_with(InspectContainerArgs::default().size(true))
    ///         .await?;
    ///
    ///     let container_size = container.size_root_fs
    ///         .map(|size| size.to_string())
    ///         .unwrap_or("unknown".into());
    ///
    ///     println!("Container status: {}", container.state.status);
    ///     println!("Container root file system size: {}", container_size);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn inspect_with(&self, args: InspectContainerArgs) -> Result<InspectContainerResponse, DecUseError> {
        let uri = self.client.url.containers().inspect(&self.container_id, args.size.unwrap_or_default());
        let response = self.client.http.get(uri)?.execute().await?;

        response
            .assert_item_status(StatusCode::OK)?
            .parse()
    }

    /// Abort a running container, using the default process signal (as determined
    /// by the Docker Engine and/or the container's configuration or the configuration
    /// of the image the container is based on).
    pub async fn kill<S: Into<String>>(&self) -> Result<(), DecUseError> {
        self.kill_opt(None).await
    }

    /// Send a signal to a container.
    ///
    /// Multiple signals are supported, not just SIGKILL.
    ///
    /// # Arguments
    /// * `signal` - name of signal to send
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").kill_with("SIGTERM").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn kill_with<S: Into<String>>(&self, signal: S) -> Result<(), DecUseError> {
        self.kill_opt(Some(signal.into())).await
    }

    async fn kill_opt(&self, signal: Option<String>) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().kill(&self.container_id, signal)?;
        let response = self.client.http.post(uri)?.execute().await?;

        response
            .assert_unit_status(StatusCode::NO_CONTENT)
    }

    /// Pause a running container.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").pause().await?;
    ///     Ok(())
    /// }
    /// ```
    #[cfg(not(windows))]  // Docker for Windows does not support pausing containers.
    pub async fn pause(&self) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().pause(&self.container_id);
        let response = self.client.http.post(uri)?.execute().await?;

        response
            .assert_unit_status(StatusCode::NO_CONTENT)
    }

    /// Delete a stopped container.
    ///
    /// Remove requests are NOT idempotent.
    pub async fn remove(&self) -> Result<(), DecUseError> {
        self.remove_with(RemoveContainerArgs::default()).await
    }

    /// Delete a container.
    ///
    /// Remove requests are NOT idempotent; attempting to remove a removed container will return an error.
    ///
    /// # Arguments
    /// * `args` are additional request arguments for the removal.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    /// use passivized_docker_engine_client::requests::RemoveContainerArgs;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     let args = RemoveContainerArgs::default()
    ///         .remove_volumes(true);
    ///
    ///     dec.container("example").remove_with(args).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn remove_with(&self, args: RemoveContainerArgs) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().remove(&self.container_id, args)?;
        let response = self.client.http.delete(uri)?.execute().await?;

        response
            .assert_unit_status(StatusCode::NO_CONTENT)
    }

    /// Rename an existing container.
    ///
    /// # Arguments
    /// * `new_name` - New name for the container.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").rename("example2").await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn rename<NN: Into<String>>(&self, new_name: NN) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().rename(&self.container_id, new_name.into());
        let response = self.client.http.post(uri)?.execute().await?;

        response
            .assert_unit_status(StatusCode::NO_CONTENT)
    }

    /// Start an existing container.
    ///
    /// This is idempotent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").start().await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn start(&self) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().start(&self.container_id);
        let response = self.client.http.post(uri)?.execute().await?;

        response
            // See https://docs.docker.com/engine/api/v1.41/#tag/Container/operation/ContainerStart
            .assert_unit_status_in(&[
                // No error
                StatusCode::NO_CONTENT,
                // Already started
                StatusCode::NOT_MODIFIED
            ])
    }

    /// Stop a running container.
    ///
    /// This is idempotent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").stop().await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn stop(&self) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().stop(&self.container_id);
        let response = self.client.http.post(uri)?.execute().await?;

        response
            // See https://docs.docker.com/engine/api/v1.41/#tag/Container/operation/ContainerStop
            .assert_unit_status_in(&[
                // No error
                StatusCode::NO_CONTENT,
                // Already stopped
                StatusCode::NOT_MODIFIED
            ])
    }

    /// Get a list of processes running inside the container.
    pub async fn top(&self) -> Result<TopResponse, DecUseError> {
        self.top_opt(None).await
    }

    /// Get a list of processes running inside the container, customizing the output.
    pub async fn top_with(&self, ps_args: String) -> Result<TopResponse, DecUseError> {
        self.top_opt(Some(ps_args)).await
    }

    async fn top_opt(&self, ps_args: Option<String>) -> Result<TopResponse, DecUseError> {
        let uri = self.client.url.containers().top(&self.container_id, ps_args)?;
        let response = self.client.http.get(uri)?.execute().await?;

        response
            .assert_item_status(StatusCode::OK)?
            .parse()
    }

    /// Unpause a paused container.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").unpause().await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    #[cfg(not(windows))]  // Docker for Windows does not support pausing containers.
    pub async fn unpause(&self) -> Result<(), DecUseError> {
        let uri = self.client.url.containers().unpause(&self.container_id);
        let response = self.client.http.post(uri)?.execute().await?;

        response
            .assert_unit_status(StatusCode::NO_CONTENT)
    }

    /// Wait for a container to reach a specific state.
    ///
    /// For process stop states, blocks until the container stops, then returns the exit code.
    ///
    /// # Arguments
    /// `condition` - Desired condition to wait for.
    ///
    /// # Example
    ///
    /// ```rust
    /// use passivized_docker_engine_client::DockerEngineClient;
    /// use passivized_docker_engine_client::errors::DecError;
    /// use passivized_docker_engine_client::requests::WaitCondition;
    ///
    /// async fn example() -> Result<(), DecError> {
    ///     let dec = DockerEngineClient::new()?;
    ///
    ///     dec.container("example").wait(WaitCondition::NotRunning).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn wait(&self, condition: WaitCondition) -> Result<WaitResponse, DecUseError> {
        let uri = self.client.url.containers().wait(&self.container_id, condition);
        let response = self.client.http.post(uri)?.execute().await?;

        response
            .assert_item_status(StatusCode::OK)?
            .parse()
    }

}