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
//! Various utilities.
//!
//! All the little things that are useful through the spirit's or user's code, and don't really fit
//! anywhere else.

use std::env;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;

use err_context::prelude::*;
use log::warn;
use serde::de::{Deserializer, Error as DeError, Unexpected};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

use crate::AnyError;

/// Tries to read an absolute path from the given OS string.
///
/// This converts the path to PathBuf. Then it tries to make it absolute and canonical, so changing
/// current directory later on doesn't make it invalid.
///
/// The function never fails. However, the substeps (finding current directory to make it absolute
/// and canonization) might fail. In such case, the failing step is skipped.
///
/// The motivation is parsing command line arguments using the [`structopt`] crate. Users are used
/// to passing relative paths to command line (as opposed to configuration files). However, if the
/// daemon changes the current directory (for example during daemonization), the relative paths now
/// point somewhere else.
///
/// # Examples
///
/// ```rust
/// use std::path::PathBuf;
///
/// use structopt::StructOpt;
///
/// #[derive(Debug, StructOpt)]
/// struct MyOpts {
///     #[structopt(short = "p", parse(from_os_str = spirit::utils::absolute_from_os_str))]
///     path: PathBuf,
/// }
///
/// # fn main() { }
/// ```
pub fn absolute_from_os_str(path: &OsStr) -> PathBuf {
    let mut current = env::current_dir().unwrap_or_else(|e| {
        warn!(
            "Some paths may not be turned to absolute. Couldn't read current dir: {}",
            e,
        );
        PathBuf::new()
    });
    current.push(path);
    if let Ok(canonicized) = current.canonicalize() {
        canonicized
    } else {
        current
    }
}

/// An error returned when the user passes a key-value option without the equal sign.
///
/// Some internal options take a key-value pairs on the command line. If such option is expected,
/// but it doesn't contain the equal sign, this is the used error.
#[derive(Copy, Clone, Debug)]
pub struct MissingEquals;

impl Display for MissingEquals {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        write!(fmt, "Missing = in map option")
    }
}

impl Error for MissingEquals {}

/// A helper for deserializing map-like command line arguments.
///
/// # Examples
///
/// ```rust
/// # use structopt::StructOpt;
/// #[derive(Debug, StructOpt)]
/// struct MyOpts {
///     #[structopt(
///         short = "D",
///         long = "define",
///         parse(try_from_str = spirit::utils::key_val),
///         number_of_values(1),
///     )]
///     defines: Vec<(String, String)>,
/// }
///
/// # fn main() {}
/// ```
pub fn key_val<K, V>(opt: &str) -> Result<(K, V), AnyError>
where
    K: FromStr,
    K::Err: Error + Send + Sync + 'static,
    V: FromStr,
    V::Err: Error + Send + Sync + 'static,
{
    let pos = opt.find('=').ok_or(MissingEquals)?;
    Ok((opt[..pos].parse()?, opt[pos + 1..].parse()?))
}

/// A wrapper to hide a configuration field from logs.
///
/// This acts in as much transparent way as possible towards the field inside. It only replaces the
/// [`Debug`] and [`Serialize`] implementations with returning `"******"`.
///
/// The idea is if the configuration contains passwords, they shouldn't leak into the logs.
/// Therefore, wrap them in this, eg:
///
/// ```rust
/// use std::io::Write;
/// use std::str;
///
/// use spirit::utils::Hidden;
///
/// #[derive(Debug)]
/// struct Cfg {
///     username: String,
///     password: Hidden<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let cfg = Cfg {
///     username: "me".to_owned(),
///     password: "secret".to_owned().into(),
/// };
///
/// let mut buffer: Vec<u8> = Vec::new();
/// write!(&mut buffer, "{:?}", cfg)?;
/// assert_eq!(r#"Cfg { username: "me", password: "******" }"#, str::from_utf8(&buffer)?);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "cfg-help", derive(structdoc::StructDoc))]
#[repr(transparent)]
#[serde(transparent)]
pub struct Hidden<T>(pub T);

impl<T> From<T> for Hidden<T> {
    fn from(val: T) -> Self {
        Hidden(val)
    }
}

impl<T> Deref for Hidden<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> DerefMut for Hidden<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

impl<T> Debug for Hidden<T> {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        write!(fmt, "\"******\"")
    }
}

impl<T> Serialize for Hidden<T> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str("******")
    }
}

/// Serialize a duration.
///
/// This can be used in configuration structures containing durations. See [`deserialize_duration`]
/// for the counterpart.
///
/// The default serialization produces human unreadable values, this is more suitable for dumping
/// configuration users will read.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
/// struct Cfg {
///     #[serde(
///         serialize_with = "spirit::utils::serialize_duration",
///         deserialize_with = "spirit::utils::deserialize_duration",
///     )]
///     how_long: Duration,
/// }
/// ```
pub fn serialize_duration<S: Serializer>(dur: &Duration, s: S) -> Result<S::Ok, S::Error> {
    s.serialize_str(&humantime::format_duration(*dur).to_string())
}

/// Deserialize a human-readable duration.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
/// struct Cfg {
///     #[serde(
///         serialize_with = "spirit::utils::serialize_duration",
///         deserialize_with = "spirit::utils::deserialize_duration",
///     )]
///     how_long: Duration,
/// }
/// ```
pub fn deserialize_duration<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
    let s = String::deserialize(d)?;

    humantime::parse_duration(&s)
        .map_err(|_| DeError::invalid_value(Unexpected::Str(&s), &"Human readable duration"))
}

/// Deserialize an `Option<Duration>` using the [`humantime`] crate.
///
/// This allows reading human-friendly representations of time, like `30s` or `5days`. It should be
/// paired with [`serialize_opt_duration`]. Also, to act like [`Option`] does when deserializing by
/// default, the `#[serde(default)]` is recommended.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
/// struct Cfg {
///     #[serde(
///         serialize_with = "spirit::utils::serialize_opt_duration",
///         deserialize_with = "spirit::utils::deserialize_opt_duration",
///         default,
///     )]
///     how_long: Option<Duration>,
/// }
/// ```
pub fn deserialize_opt_duration<'de, D: Deserializer<'de>>(
    d: D,
) -> Result<Option<Duration>, D::Error> {
    if let Some(dur) = Option::<String>::deserialize(d)? {
        humantime::parse_duration(&dur)
            .map_err(|_| DeError::invalid_value(Unexpected::Str(&dur), &"Human readable duration"))
            .map(Some)
    } else {
        Ok(None)
    }
}

/// Serialize an `Option<Duration>` in a human friendly form.
///
/// See the [`deserialize_opt_duration`] for more details and an example.
pub fn serialize_opt_duration<S: Serializer>(
    dur: &Option<Duration>,
    s: S,
) -> Result<S::Ok, S::Error> {
    match dur {
        Some(d) => serialize_duration(d, s),
        None => s.serialize_none(),
    }
}

/// Remove the signals handling termination.
///
/// There's a common pattern of handling termination signals (`CTRL+C`, mostly). The first one
/// initiates a graceful shutdown. But in case the shutdown takes a long time, the user can press
/// `CTRL+C` again and expect to shut down immediately (in more unclean way, possibly).
///
/// On the application side, it is handled by resetting the signal handlers to their defaults after
/// receiving the first one. This can be used to such thing (it resets the signal handlers for
/// `SIGTERM`, `SIGINT`, `SIGQUIT`).
///
/// # Warning
///
/// This resets the signal handlers, but doesn't remove the *hooks*. Furthermore, this is a global
/// action ‒ it doesn't reset only the ones of [`spirit`][crate], but of everything in the
/// application.
///
/// Also, this example runs the cleanup as part of the normal `spirit` background thread. If the
/// shutdown is being slow (or stuck) in there before calling the `on_terminate` here, it won't
/// have effect. Therefore it is a good idea to register this earlier than later.
///
/// # Examples
///
/// ```rust
/// use spirit::{utils, Empty, Spirit};
/// use spirit::prelude::*;
///
/// Spirit::<Empty, Empty>::new()
///     .on_terminate(utils::cleanup_signals)
///     .run(|_| {
///         Ok(())
///     })
/// ```
pub fn cleanup_signals() {
    for i in &[libc::SIGTERM, libc::SIGINT, libc::SIGQUIT] {
        if let Err(e) = signal_hook::cleanup::cleanup_signal(*i) {
            warn!("Failed to remove signal handler {}: {}", i, e.display(": "));
        }
    }
}

/// Checks if value is default.
///
/// Useful in `#[serde(skip_serializing_if = "is_default")]`
pub fn is_default<T: Default + PartialEq>(v: &T) -> bool {
    v == &T::default()
}

/// Checks if value is set to true.
///
/// Useful in `#[serde(skip_serializing_if = "is_true")]`
pub fn is_true(v: &bool) -> bool {
    *v
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::net::{AddrParseError, IpAddr};
    use std::num::ParseIntError;

    use super::*;

    #[test]
    fn abs() {
        let current = env::current_dir().unwrap();
        let parent = absolute_from_os_str(&OsString::from(".."));
        assert!(parent.is_absolute());
        assert!(current.starts_with(parent));

        let child = absolute_from_os_str(&OsString::from("this-likely-doesn't-exist"));
        assert!(child.is_absolute());
        assert!(child.starts_with(current));
    }

    /// Valid inputs for the key-value parser
    #[test]
    fn key_val_success() {
        assert_eq!(
            ("hello".to_owned(), "world".to_owned()),
            key_val("hello=world").unwrap()
        );
        let ip: IpAddr = "192.0.2.1".parse().unwrap();
        assert_eq!(("ip".to_owned(), ip), key_val("ip=192.0.2.1").unwrap());
        assert_eq!(("count".to_owned(), 4), key_val("count=4").unwrap());
    }

    /// The extra equals sign go into the value part.
    #[test]
    fn key_val_extra_equals() {
        assert_eq!(
            ("greeting".to_owned(), "hello=world".to_owned()),
            key_val("greeting=hello=world").unwrap(),
        );
    }

    /// Test when the key or value doesn't get parsed.
    #[test]
    fn key_val_parse_fail() {
        key_val::<String, IpAddr>("hello=192.0.2.1.0")
            .unwrap_err()
            .downcast_ref::<AddrParseError>()
            .expect("Different error returned");
        key_val::<usize, String>("hello=world")
            .unwrap_err()
            .downcast_ref::<ParseIntError>()
            .expect("Different error returned");
    }

    #[test]
    fn key_val_missing_eq() {
        key_val::<String, String>("no equal sign")
            .unwrap_err()
            .downcast_ref::<MissingEquals>()
            .expect("Different error returned");
    }
}