Skip to main content

languagetool_rust/cli/
docker.rs

1//! Structures and methods to easily manipulate Docker images, especially for
2//! LanguageTool applications.
3
4use std::process::{self, Output, Stdio};
5
6use clap::{Args, Parser};
7use termcolor::StandardStream;
8
9use crate::{
10    api::server::ServerClient,
11    error::{exit_status_error, Error, Result},
12};
13
14use super::ExecuteSubcommand;
15
16/// Commands to pull, start and stop a `LanguageTool` container using Docker.
17#[derive(Debug, Clone, Args)]
18pub struct Docker {
19    /// Image or repository from a registry.
20    #[clap(
21        default_value = "erikvl87/languagetool",
22        env = "LANGUAGETOOL_DOCKER_IMAGE"
23    )]
24    name: String,
25    /// Path to Docker's binaries.
26    #[clap(
27        short = 'b',
28        long,
29        default_value = "docker",
30        env = "LANGUAGETOOL_DOCKER_BIN"
31    )]
32    bin: String,
33    /// Name assigned to the container.
34    #[clap(long, default_value = "languagetool", env = "LANGUAGETOOL_DOCKER_NAME")]
35    container_name: String,
36    /// Publish a container's port(s) to the host.
37    #[clap(
38        short = 'p',
39        long,
40        default_value = "8010:8010",
41        env = "LANGUAGETOOL_DOCKER_PORT"
42    )]
43    port: String,
44    /// Docker action.
45    #[clap(subcommand)]
46    action: Action,
47}
48
49#[derive(clap::Subcommand, Clone, Debug)]
50/// Enumerate supported Docker actions.
51enum Action {
52    /// Pull a docker docker image.
53    ///
54    /// Alias to `{docker.bin} pull {docker.name}`.
55    Pull,
56    /// Start a (detached) docker container.
57    ///
58    /// Alias to `{docker.bin} run --rm -d -p {docker.port} {docker.name}`
59    Start,
60    /// Stop a docker container.
61    ///
62    /// Alias to `{docker.bin} kill $({docker.bin} ps -l -f
63    /// "name={docker.container_name}")`.
64    Stop,
65}
66
67impl Docker {
68    /// Pull a Docker image from the given repository/file/...
69    pub fn pull(&self) -> Result<Output> {
70        let output = process::Command::new(&self.bin)
71            .args(["pull", &self.name])
72            .stdout(Stdio::inherit())
73            .stderr(Stdio::inherit())
74            .output()
75            .map_err(|_| Error::CommandNotFound(self.bin.to_string()))?;
76
77        exit_status_error(&output.status)?;
78
79        Ok(output)
80    }
81
82    /// Start a Docker container with given specifications.
83    pub fn start(&self) -> Result<Output> {
84        let output = process::Command::new(&self.bin)
85            .args([
86                "run",
87                "--rm",
88                "--name",
89                &self.container_name,
90                "-d",
91                "-p",
92                "8010:8010",
93                &self.name,
94            ])
95            .stdout(Stdio::inherit())
96            .stderr(Stdio::inherit())
97            .output()
98            .map_err(|_| Error::CommandNotFound(self.bin.to_string()))?;
99
100        exit_status_error(&output.status)?;
101
102        Ok(output)
103    }
104
105    /// Stop the latest Docker container with the given name.
106    pub fn stop(&self) -> Result<Output> {
107        let output = process::Command::new(&self.bin)
108            .args([
109                "ps",
110                "-l",
111                "-f",
112                &format!("name={}", self.container_name),
113                "-q",
114            ])
115            .stderr(Stdio::inherit())
116            .output()
117            .map_err(|_| Error::CommandNotFound(self.bin.to_string()))?;
118
119        exit_status_error(&output.status)?;
120
121        let docker_id: String = String::from_utf8_lossy(&output.stdout)
122            .chars()
123            .filter(|c| c.is_alphanumeric()) // This avoids newlines
124            .collect();
125
126        let output = process::Command::new(&self.bin)
127            .args(["kill", &docker_id])
128            .stdout(Stdio::inherit())
129            .stderr(Stdio::inherit())
130            .output()?;
131
132        exit_status_error(&output.status)?;
133
134        Ok(output)
135    }
136
137    /// Run a Docker command according to `self.action`.
138    pub fn run_action(&self) -> Result<Output> {
139        match self.action {
140            Action::Pull => self.pull(),
141            Action::Start => self.start(),
142            Action::Stop => self.stop(),
143        }
144    }
145}
146
147/// Commands to easily run a LanguageTool server with Docker.
148#[derive(Debug, Parser)]
149pub struct Command {
150    /// Actual command arguments.
151    #[command(flatten)]
152    pub docker: Docker,
153}
154
155impl ExecuteSubcommand for Command {
156    /// Execute the `docker` subcommand.
157    async fn execute(self, _stdout: StandardStream, _: ServerClient) -> Result<()> {
158        self.docker.run_action()?;
159        Ok(())
160    }
161}