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
mod child_hook;
pub mod child_output;
mod child_repeat;

use super::logger;
use chrono::prelude::*;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{Error as ioError, ErrorKind, Read, Result};
use std::time;
use yaml_rust::YamlLoader;

use child_hook::Hooks;
use child_output::Output;
use child_repeat::Repeat;

#[derive(Debug)]
pub struct Config {
    comm: String,
    pub stdout: Option<Output>,
    pub stderr: Option<Output>,
    repeat: Option<Repeat>,
    hooks: Option<Hooks>,

    pub child_id: Option<u32>,
    pub start_time: Option<DateTime<Local>>,
}

impl Config {
    pub fn new(comm: String) -> Self {
        Config {
            comm: comm,
            stdout: None,
            stderr: None,
            child_id: None,
            repeat: None,
            hooks: None,
            start_time: None,
        }
    }

    fn read_from_str(input: &str) -> Result<Self> {
        let temp = YamlLoader::load_from_str(input);

        let mut result: Self;
        match temp {
            Ok(docs) => {
                let doc = &docs[0];

                result = Self::new(doc["command"].clone().into_string().unwrap());

                if let Ok(output) = Output::new(doc["output"].clone()) {
                    for (field, data) in output {
                        if field == "stdout".to_string() {
                            result.stdout = Some(data);
                        } else if field == "stderr".to_string() {
                            result.stderr = Some(data);
                        }
                    }
                }

                result.repeat = match Repeat::new(&doc["repeat"]) {
                    Ok(r) => Some(r),
                    Err(e) => {
                        if e.kind() != ErrorKind::NotFound {
                            println!("{}", logger::timelog(e.description()));
                        }
                        None
                    }
                };

                result.hooks = match Hooks::new(&doc["hooks"]) {
                    Ok(h) => Some(h),
                    Err(e) => {
                        if e.kind() != ErrorKind::NotFound {
                            println!("{}", logger::timelog(e.description()));
                        }
                        None
                    }
                }
            }

            Err(e) => return Err(ioError::new(ErrorKind::Other, e.description().to_string())),
        }

        Ok(result)
    }

    pub fn read_from_yaml_file(filename: &str) -> Result<Self> {
        let contents = File::open(filename);
        let mut string_result = String::new();
        match contents {
            Ok(mut cont) => {
                let _ = cont.read_to_string(&mut string_result);
                return Self::read_from_str(string_result.as_str());
            }

            Err(e) => return Err(ioError::new(ErrorKind::Other, e.description().to_string())),
        }
    }

    pub fn split_args(&self) -> (String, Option<String>) {
        let split_comm: Vec<_> = self.comm.splitn(2, ' ').collect();

        if split_comm.len() > 1 {
            return (split_comm[0].to_string(), Some(split_comm[1].to_string()));
        }

        (split_comm[0].to_string(), None)
    }

    pub fn is_repeat(&self) -> bool {
        if let Some(_) = self.repeat {
            return true;
        }
        false
    }

    pub fn to_duration(&self) -> Result<time::Duration> {
        if !self.is_repeat() {
            return Err(ioError::new(
                ErrorKind::Other,
                format!("do not find repeat value"),
            ));
        }

        match self.repeat.as_ref().unwrap().seconds.clone() {
            0 => Err(ioError::new(
                ErrorKind::Other,
                format!("repeat time cannot be 0"),
            )),
            d => Ok(time::Duration::from_secs(d as u64)),
        }
    }

    pub fn repeat_command(&self) -> Result<String> {
        if !self.is_repeat() {
            return Err(ioError::new(
                ErrorKind::Other,
                format!("do not find repeat value"),
            ));
        }

        Ok(self.repeat.as_ref().unwrap().action.clone())
    }

    pub fn has_hook(&self) -> bool {
        if let Some(h) = &self.hooks {
            return h.has_hook();
        }
        false
    }

    pub fn get_hook(&self, key: &String) -> Option<String> {
        if self.has_hook() {
            return Some(
                self.hooks
                    .as_ref()
                    .unwrap()
                    .get(key)
                    .as_ref()
                    .unwrap()
                    .to_string(),
            );
        }

        None
    }

    pub fn get_hook_command(&self, key: &String) -> Option<String> {
        if self.has_hook() {
            return self.hooks.as_ref().unwrap().get_hook_command(key);
        }

        None
    }

    pub fn get_hook_detail(&self, key: &String) -> Option<Vec<String>> {
        if self.has_hook() {
            return self.hooks.as_ref().unwrap().get_hook_detail(key);
        }
        None
    }
}

impl Clone for Config {
    fn clone(&self) -> Self {
        Config {
            comm: self.comm.clone(),
            stdout: self.stdout.clone(),
            stderr: self.stderr.clone(),
            child_id: self.child_id,
            repeat: self.repeat.clone(),
            hooks: self.hooks.clone(),
            start_time: self.start_time.clone(),
        }
    }
}

impl fmt::Display for Config {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "  command is: {}\n  stdout is: {}\n  stderr is: {}\n  child id is: {}\n  start time: {:?}\n  repeat is: {}\n  hooks are:\n{}",
            self.comm,
            self.stdout.as_ref().unwrap_or(&Output::new_empty()),
            self.stderr.as_ref().unwrap_or(&Output::new_empty()),
            self.child_id.as_ref().unwrap_or(&(0 as u32)),
            {if let Some(t) = self.start_time{
                t.format("%Y-%m-%d %H:%M:%S").to_string()
            }else {
                String::from("none")
            }},
            //Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
            self.repeat.as_ref().unwrap_or(&Repeat::new_empty()),
            self.hooks.as_ref().unwrap_or(&Hooks::new_empty())
        )
    }
}

// tiny tests below
#[cfg(test)]
mod tests {
    use super::super::server::start_new_child;
    use super::*;

    //#[test]
    fn command_argvs() {
        let con = dbg!(Config::read_from_yaml_file("./test/argv.yml")).unwrap();
        let (comm, argvs) = con.split_args();
        println!("command: {}", comm);

        println!("{:?}", con.split_args());

        println!("{:?}", argvs.unwrap().split(' ').collect::<Vec<&str>>());
    }

    //#[test]
    fn run_ls() {
        let mut con = dbg!(Config::read_from_yaml_file("./test/ls.yaml")).unwrap();

        let _ = dbg!(start_new_child(&mut con));
    }

    //#[test]
    fn read_hooks() {
        let input0 = "
command: test
hooks:
  - prehook: start child1
  - posthook: start child2
  - posthook: start child3
";
        println!("read_hooks 0: {:?}", Config::read_from_str(input0));

        let input1 = "
command: test
hooks:
";

        println!("read_hooks 1: {:?}", Config::read_from_str(input1));
    }

    #[test]
    fn test_printout_config() {
        let input0 = "
command: test
output:
  - stdout: aaaaaa
    mode: append
hooks:
#  - prehook: start child1
#  - posthook: start child2
#  - posthook: start child3
repeat:
  action: restart
  seconds: 5
";
        let conf = Config::read_from_str(input0).unwrap();

        println!("whole config is:\n{}", conf);
    }

}