about summary refs log tree commit diff stats
path: root/src/service.rs
blob: 97dc359cc0b2f10402cfdcad9bc9332bc899d79b (plain) (blame)
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
use serde::{Deserialize, Serialize};
use std::{
    fs::File,
    io::{BufRead, BufReader, Write},
    path::PathBuf,
    process::{Child, Command, Stdio},
};
use uuid::Uuid;

pub enum ServiceState {
    Running,
    Failed,
    Stopped,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ServiceConf {
    uuid: Uuid,
    name: String,
    command: String,
    args: Option<String>,
    directory: Option<PathBuf>,
    autostart: bool,
    oneshot: Option<bool>,
}
impl Default for ServiceConf {
    fn default() -> Self {
        Self::new()
    }
}
impl ServiceConf {
    /// Returns a new empty `ServiceConf`
    pub fn new() -> Self {
        Self {
            uuid: Uuid::new_v4(),
            name: String::new(),
            command: String::new(),
            args: None,
            directory: None,
            autostart: false,
            oneshot: None,
        }
    }
    /// Returns a new `ServiceConf` from parts.
    pub fn from_parts(
        uuid: Uuid,
        name: String,
        command: String,
        args: Option<String>,
        directory: Option<PathBuf>,
        autostart: bool,
        oneshot: Option<bool>,
    ) -> Self {
        Self {
            uuid,
            name,
            command,
            args,
            directory,
            autostart,
            oneshot,
        }
    }
    /// Returns a new `ServiceConf` from parts with new uuid.
    pub fn new_from_parts(
        name: String,
        command: String,
        args: Option<String>,
        directory: Option<PathBuf>,
        autostart: bool,
        oneshot: Option<bool>,
    ) -> Self {
        Self {
            uuid: Uuid::new_v4(),
            name,
            command,
            args,
            directory,
            autostart,
            oneshot,
        }
    }
    /// Returns the `uuid::Uuid` associated with the service config
    pub fn get_uuid(&self) -> &Uuid {
        &self.uuid
    }
    /// Returns the name of the described service
    pub fn get_name(&self) -> &str {
        &self.name
    }
    /// Returns the command of the described service
    pub fn get_command(&self) -> &str {
        &self.command
    }
    /// Returns the args of the described service
    pub fn get_args(&self) -> &Option<String> {
        &self.args
    }
    /// Returns the work directory of the described service
    pub fn get_work_dir(&self) -> &Option<PathBuf> {
        &self.directory
    }
    /// Returns the autostart status of the described service
    pub fn get_autostart(&self) -> bool {
        self.autostart
    }
    /// Returns the oneshot value of the described service
    pub fn get_oneshot(&self) -> &Option<bool> {
        &self.oneshot
    }
    /// Sets the name of the described service
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.name = String::from(name);
        self
    }
    /// Sets the command of the described service
    pub fn command(&mut self, command: &str) -> &mut Self {
        self.command = String::from(command);
        self
    }
    /// Sets the args of the described service
    pub fn args(&mut self, args: &Option<String>) -> &mut Self {
        self.args = args.clone();
        self
    }
    /// Sets the work directory of the described service
    pub fn work_dir(&mut self, work_dir: &Option<PathBuf>) -> &mut Self {
        self.directory = work_dir.clone();
        self
    }
    /// Sets the autostart value of the described service
    pub fn autostart(&mut self, autostart: bool) -> &mut Self {
        self.autostart = autostart;
        self
    }
    /// Sets the oneshot flag for the described service
    pub fn oneshot(&mut self, oneshot: bool) -> &mut Self {
        if oneshot {
            self.oneshot = Some(true);
        } else {
            self.oneshot = None;
        }
        self
    }
    /// Builds a Service from this object
    #[inline]
    pub fn build(&self) -> Result<Service, Box<dyn std::error::Error>> {
        Service::from_conf(&self)
    }
}

#[derive(Debug)]
pub struct Service {
    conf: ServiceConf,
    proc: Option<Child>,
    pub outpath: Option<PathBuf>,
    pub errpath: Option<PathBuf>,
}
impl Default for Service {
    fn default() -> Self {
        Self::new()
    }
}
impl<'a> Service {
    /// Returns a new empty `Service`
    pub fn new() -> Self {
        Self {
            conf: ServiceConf::default(),
            proc: None,
            outpath: None,
            errpath: None,
        }
    }
    /// Returns a `Service` made from a `ServiceConf`.
    pub fn from_conf(conf: &ServiceConf) -> Result<Self, Box<dyn std::error::Error>> {
        let mut service = Self {
            conf: conf.to_owned(),
            proc: None,
            outpath: None,
            errpath: None,
        };
        if conf.get_autostart() {
            service.start()?;
        }
        Ok(service)
    }
    /// Gets the ServiceConf associated with the service
    #[inline]
    pub fn config(&self) -> &ServiceConf {
        &self.conf
    }
    /// Returns the name of the service
    #[inline]
    pub fn name(&self) -> &str {
        &self.config().get_name()
    }
    /// Returns the uuid of the service, shorthand for Service::config().get_uuid()
    #[inline]
    pub fn uuid(&self) -> &Uuid {
        &self.config().get_uuid()
    }
    #[inline]
    pub fn oneshot(&self) -> &Option<bool> {
        &self.config().get_oneshot()
    }
    #[inline]
    fn create_dirs(&self) -> Result<(), Box<dyn std::error::Error>> {
        match std::fs::create_dir("./logs") {
            Ok(_) => (),
            Err(ref e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
            Err(e) => return Err(Box::new(e)),
        }
        match std::fs::create_dir(format!("./logs/{}", &self.config().get_uuid())) {
            Ok(_) => (),
            Err(ref e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
            Err(e) => return Err(Box::new(e)),
        }
        Ok(())
    }
    /// Uses `tokio::process::Command` to start the service.
    pub fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.proc.is_some() {
            return Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                "Process Already Exists",
            )));
        }
        self.create_dirs()?;
        let outpath = PathBuf::from(format!(
            "./logs/{}/{}.log",
            &self.config().get_uuid(),
            &self.name()
        ));
        let errpath = PathBuf::from(format!(
            "./logs/{}/{}.err",
            &self.config().get_uuid(),
            &self.name()
        ));
        let outfile = File::options().append(true).create(true).open(&outpath)?;
        let errfile = File::options().append(true).create(true).open(&errpath)?;
        let cmd = &self.conf.command;
        let mut proc = Command::new(cmd);
        proc.stdin(Stdio::piped());
        proc.stdout(outfile);
        proc.stderr(errfile);
        if let Some(a) = &self.conf.args {
            proc.args(a.split_whitespace());
        };
        if let Some(c) = &self.conf.directory {
            proc.current_dir(c);
        };
        let child = proc.spawn()?;
        self.proc = Some(child);
        self.outpath = Some(outpath);
        self.errpath = Some(errpath);
        Ok(())
    }
    /// Returns true when process is started and false when process is stopped.
    pub fn started(&self) -> bool {
        self.proc.is_some()
    }
    /// Returns the process id
    pub fn id(&self) -> Result<u32, Box<dyn std::error::Error>> {
        if let Some(proc) = self.proc.as_ref() {
            Ok(proc.id())
        } else {
            Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "process not started",
            )))
        }
    }
    /// Returns the state of the service
    pub fn state(&mut self) -> ServiceState {
        if let Some(proc) = self.proc.as_mut() {
            match proc.try_wait() {
                Err(_) | Ok(Some(_)) => {
                    if let Some(b) = self.oneshot() {
                        if *b {
                            return ServiceState::Stopped;
                        }
                    }
                    ServiceState::Failed
                },
                Ok(None) => ServiceState::Running,
            }
        } else {
            ServiceState::Stopped
        }
    }
    /// Invokes kill on the service process
    pub fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(proc) = self.proc.as_mut() {
            proc.kill()?;
            self.proc = None;
            Ok(())
        } else {
            Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "No Process Associated with Service",
            )))
        }
    }
    /// Restarts service process
    #[inline]
    pub fn restart(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.stop()?;
        self.start()?;
        Ok(())
    }
    /// Writes to the service process' stdin, if it exists.
    pub fn write_stdin(&mut self, buf: &str) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(proc) = self.proc.as_mut() {
            let stdin = if let Some(stdin) = proc.stdin.as_mut() {
                stdin
            } else {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "No stdin handle associated with process",
                )));
            };
            stdin.write(&buf.as_bytes())?;
            stdin.flush()?;
            Ok(())
        } else {
            Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "No Process Associated with Service",
            )))
        }
    }
    /// Writes a line to the service process' stdin, if it exists.
    #[inline]
    pub fn writeln_stdin(&mut self, buf: &str) -> Result<(), Box<dyn std::error::Error>> {
        self.write_stdin(&format!("{}\n", buf))
    }
}