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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Contains a logging service with helper macro to ease integration with the cloud logging system.

use std::borrow::Cow;
use std::error;
use std::fmt::{self, Debug, Display, Formatter};
use std::mem;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::{AtomicIsize, Ordering};
use std::thread::{self, JoinHandle};

use futures::{future, Stream};
use futures::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};

use tokio_core::reactor::Core;

use {Request, Service};

const DEFAULT_LOGGING_NAME: &str = "logging";

enum Event {
    Write(Vec<u8>),
    Close,
}

struct Inner {
    tx: mpsc::UnboundedSender<Event>,
    thread: Option<JoinHandle<()>>,
}

impl Inner {
    fn new(name: Cow<'static, str>, tx: UnboundedSender<Event>, rx: UnboundedReceiver<Event>) -> Self {
        let thread = thread::Builder::new().name("logging".into()).spawn(move || {
            let mut core = Core::new().expect("failed to initialize logger event loop");
            let handle = core.handle();

            let service = Service::new(name, &handle);

            let future = rx.and_then(|event| {
                let future = match event {
                    Event::Write(buf) => {
                        // TODO: For unknown reasons this one hangs until external reconnection
                        // after sending some messages.
//                        service.call_mute_raw(0, buf).then(|tx| {
//                            drop(tx);
//                            Ok(())
//                        }).boxed()
                        service.call_mute(Request::from_buf(0, buf));
                        future::ok(())
                    }
                    Event::Close => future::err(())
                };

                Box::new(future)
            });

            drop(core.run(future.fold(0, |acc, _v| future::ok(acc))));
        }).expect("failed to create logging thread");

        Self { tx: tx, thread: Some(thread) }
    }
}

impl Drop for Inner {
    fn drop(&mut self) {
        self.tx.unbounded_send(Event::Close).unwrap();
        self.thread.take().unwrap().join().unwrap();
    }
}

/// Allowed severity levels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Severity {
    /// Debug messages can describe any debug-specific helpful information.
    Debug,
    /// Info messages usually describes how a program state changes.
    Info,
    /// Warning messages describes non-critical, but still important information.
    Warn,
    /// Error messages describes important critical information, for example a reason why a request
    /// has failed.
    Error,
}

impl Into<isize> for Severity {
    fn into(self) -> isize {
        match self {
            Severity::Debug => 0,
            Severity::Info => 1,
            Severity::Warn => 2,
            Severity::Error => 3,
        }
    }
}

impl Display for Severity {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let result = match *self {
            Severity::Debug => "debug",
            Severity::Info => "info",
            Severity::Warn => "warn",
            Severity::Error => "error",
        };

        fmt.write_str(result)
    }
}

/// An error returned when parsing a severity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeverityParseError;

impl Display for SeverityParseError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt.write_str(error::Error::description(self))
    }
}

impl error::Error for SeverityParseError {
    fn description(&self) -> &str {
        "invalid severity syntax"
    }
}

impl FromStr for Severity {
    type Err = SeverityParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "debug" => Ok(Severity::Debug),
            "info" => Ok(Severity::Info),
            "warn" | "warning" => Ok(Severity::Warn),
            "error" => Ok(Severity::Error),
            _ => Err(SeverityParseError),
        }
    }
}

/// A RAII context manager for a logging service.
///
/// This is an entry point for a logging service in the cocaine.
///
/// The `LoggerContext` creates a separate thread where the real logging service with its event
/// loop lives, and that allows to process all logging events using single TCP connection. The
/// communication with the context is done using unbounded channel, what makes emitting logging
/// events just pack-and-send operation.
///
/// Note, that the context destruction triggers wait operation until all messages are flushed into
/// the socket.
///
/// To create the logger object itself, call [`create`][create] method, which accepts an optional
/// *source* parameter - a short description where a log event came from.
///
/// There is also possible to configure a simple severity filter using [`filter`][filter] method.
///
/// [create]: #method.create
/// [filter]: #method.filter
#[derive(Clone)]
pub struct LoggerContext {
    tx: UnboundedSender<Event>,
    name: Cow<'static, str>,
    inner: Arc<Inner>,
    filter: Filter,
}

impl LoggerContext {
    /// Constructs a new logger context with the given name, that is used as a logging service's
    /// name.
    ///
    /// # Warning
    ///
    /// Beware of connecting to a service, which name is just occasionally equals with the specified
    /// one. Doing so will probably lead to reconnection after each request because of framing
    /// errors.
    ///
    /// # Examples
    ///
    /// ```
    /// use cocaine::logging::LoggerContext;
    ///
    /// let log = LoggerContext::default();
    /// assert_eq!("logging", log.name());
    ///
    /// let log = LoggerContext::new("logging::v2");
    /// assert_eq!("logging::v2", log.name());
    /// ```
    pub fn new<N>(name: N) -> Self
        where N: Into<Cow<'static, str>>
    {
        let name = name.into();

        let (tx, rx) = mpsc::unbounded();
        Self {
            tx: tx.clone(),
            name: name.clone(),
            inner: Arc::new(Inner::new(name, tx, rx)),
            filter: Filter { sev: Arc::new(AtomicIsize::new(0)) },
        }
    }

    /// Returns the associated logging service's name given at construction time.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Creates a new logger, that will log events with the given *source* argument.
    ///
    /// All loggers are associated with the context used to create them, i.e share a single
    /// underlying service and the filter.
    pub fn create<T>(&self, source: T) -> Logger
        where T: Into<Cow<'static, str>>
    {
        Logger {
            parent: self.clone(),
            source: source.into(),
        }
    }

    /// Returns a severity filtering handle.
    ///
    /// Changing the severity threshold will affect all loggers that were created using this
    /// context.
    pub fn filter(&self) -> &Filter {
        &self.filter
    }
}

impl Default for LoggerContext {
    fn default() -> Self {
        LoggerContext::new(DEFAULT_LOGGING_NAME)
    }
}

impl Debug for LoggerContext {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
        fmt.debug_struct("LoggerContext")
            .field("name", &self.name)
            .field("filter", &self.filter.get())
            .finish()
    }
}

/// Represents a filtering result for a logging event.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FilterResult {
    /// The filter accepts an event unconditionally. It should be accepted immediately without
    /// checking for other filters if any.
    Accept,
    /// The filter denies an event unconditionally. It should be denied immediately without
    /// checking for other filters if any.
    Reject,
    /// The filter is neutral with the event, i.e. it has not strong opinion what to do. It should
    /// check for other filters if any.
    Neutral,
}

/// A logger interface.
///
/// Implementations can be used in [`cocaine_log!`][log!] macro.
///
/// [log!]: ../macro.cocaine_log.html
pub trait Log {
    /// Returns a logger name, that is used as a *source* parameter.
    fn source(&self) -> &str;

    /// Checks whether an event with the specified severity can be logged.
    fn filter(&self, sev: Severity) -> FilterResult;

    #[doc(hidden)]
    /// Emits a new already properly encoded logging event.
    ///
    /// # Warning
    ///
    /// Do not use this method directly, use [`cocaine_log!`][log!] macro instead. Violating this
    /// rule may lead to repeatedly disconnection from the real logging service due to framing
    /// error. The reason is - a `buf` argument must be properly encoded.
    ///
    /// [log!]: ../macro.cocaine_log.html
    fn __emit(&self, buf: Vec<u8>) {
        mem::drop(buf);
    }
}

/// Logger allows to log events directly into the Cocaine Logging Service.
///
/// Meant to be used in conjunction with [`cocaine_log!`][log!] macro.
///
/// [log!]: ../macro.cocaine_log.html
#[derive(Debug, Clone)]
pub struct Logger {
    parent: LoggerContext,
    source: Cow<'static, str>,
}

impl Logger {
    /// Returns the associated logging service's name given at construction time.
    pub fn name(&self) -> &str {
        self.parent.name()
    }
}

impl Log for Logger {
    fn source(&self) -> &str {
        &self.source
    }

    fn filter(&self, sev: Severity) -> FilterResult {
        let sev: isize = sev.into();

        if sev >= self.parent.filter().get() {
            FilterResult::Accept
        } else {
            FilterResult::Reject
        }
    }

    fn __emit(&self, buf: Vec<u8>) {
        self.parent.tx.unbounded_send(Event::Write(buf)).unwrap();
    }
}

/// Severity filter handle.
///
/// A `Filter` allows to configure the severity level threshold for logging events. All events with
/// severity less than the specified will be rejected immediately.
#[derive(Clone, Debug)]
pub struct Filter {
    sev: Arc<AtomicIsize>,
}

impl Filter {
    /// Returns currently set severity threshold.
    pub fn get(&self) -> isize {
        self.sev.load(Ordering::Relaxed)
    }

    /// Sets the severity threshold.
    ///
    /// All logging events with severity less than the specified threshold will be dropped.
    pub fn set(&self, sev: isize) {
        self.sev.store(sev, Ordering::Relaxed)
    }
}

/// Logs a message using logger into the Logging Service.
///
/// This macro supports the standard lazy formatting using `format!` with all its compile-time type
/// and positional checking.
///
/// Since Cocaine Logging is a structured logger, additional attributes can be attached to an event.
///
/// # Examples.
///
/// ```no_run
/// #[macro_use]
/// extern crate cocaine;
///
/// use cocaine::logging::{LoggerContext, Severity};
///
/// # fn main() {
/// let ctx = LoggerContext::default();
/// let log = ctx.create("app/example");
///
/// cocaine_log!(log, Severity::Info, "nginx/1.6 configured");
/// cocaine_log!(log, Severity::Info, "{} {} HTTP/1.1 {} {}", "GET", "/static/image.png", 404, 347);
/// # }
/// ```
///
/// You can additionally attach any number of key-value attributes:
///
/// ```no_run
/// #[macro_use]
/// extern crate cocaine;
///
/// use cocaine::logging::{LoggerContext, Severity};
///
/// # fn main() {
/// let ctx = LoggerContext::default();
/// let log = ctx.create("app/example");
///
/// cocaine_log!(log, Severity::Info, "nginx/1.6 configured"; {
///     config: "/etc/nginx/nginx.conf",
///     elapsed: 42.15,
/// });
///
/// cocaine_log!(log, Severity::Warn, "client stopped connection before send body completed"; {
///     host: "::1",
///     port: 10053,
/// });
///
/// cocaine_log!(log, Severity::Error, "file does not exist: {}", "/var/www/favicon.ico"; {
///     path: "/",
///     cache: true,
///     method: "GET",
///     version: 1.1,
///     protocol: "HTTP",
/// });
/// # }
/// ```
#[macro_export]
macro_rules! cocaine_log(
    (__unwrap # {}) => {
        &[0u8; 0]
    };
    (__unwrap # {$($name:ident: $val:expr,)+}) => {
        ($((stringify!($name), &$val)),+,)
    };
    (__execute # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr, {$($name:ident: $val:expr,)*}) => {{
        extern crate rmp_serde as rmps;

        rmps::to_vec(&($sev, $src, format!($fmt, $($args)*), cocaine_log!(__unwrap # {$($name: $val,)*})))
    }};
    (__split # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr, ; {$($name:ident: $val:expr,)*}) => {
        cocaine_log!(__execute # {$($args)*}, $src, $sev, $fmt, {$($name: $val,)*})
    };
    (__split # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr, $arg:tt $($kwargs:tt)*) => {
        cocaine_log!(__split # {$($args)* $arg}, $src, $sev, $fmt, $($kwargs)*)
    };
    (__split # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr; {$($name:ident: $val:expr,)*}) => {
        cocaine_log!(__execute # {$($args)*}, $src, $sev, $fmt, {$($name: $val,)*})
    };
    (__split # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr,) => {
        cocaine_log!(__execute # {$($args)*}, $src, $sev, $fmt, {})
    };
    (__split # {$($args:tt)*}, $src:expr, $sev:expr, $fmt:expr) => {
        cocaine_log!(__execute # {$($args)*}, $src, $sev, $fmt, {})
    };
    (__test # $src:expr, $sev:expr, $($args:tt)*) => {
        cocaine_log!(__split # {}, $src, $sev, $($args)*)
    };
    ($log:expr, $sev:expr, $($args:tt)*) => {{
        #[allow(unused)]
        use cocaine::logging::{FilterResult, Log};

        match $log.filter($sev) {
            FilterResult::Accept |
            FilterResult::Neutral => {
                let sev: isize = $sev.into();
                $log.__emit(cocaine_log!(__split # {}, $log.source(), sev, $($args)*)
                    .expect("failed to serialize logging event frame"));
            }
            FilterResult::Reject => {}
        }
    }};
);

#[cfg(test)]
mod tests {
    extern crate rmpv;

    use rmpv::Value;

    #[test]
    fn test_macro_without_args() {
        let buf = cocaine_log!(__test # "test", 1, "nginx/1.6 configured").unwrap();
        let expected = Value::Array(vec![
            Value::from(1),
            Value::from("test"),
            Value::from("nginx/1.6 configured"),
            Value::Array(vec![])
        ]);
        assert_eq!(expected, rmpv::decode::read_value(&mut &buf[..]).unwrap());
    }

    #[test]
    fn test_macro_with_args() {
        let buf = cocaine_log!(__test # "test", 1, "{} {} HTTP/1.1 {} {}", "GET", "/static/image.png", 404, 347).unwrap();
        let expected = Value::Array(vec![
            Value::from(1),
            Value::from("test"),
            Value::from("GET /static/image.png HTTP/1.1 404 347"),
            Value::Array(vec![])
        ]);
        assert_eq!(expected, rmpv::decode::read_value(&mut &buf[..]).unwrap());
    }

    #[test]
    fn test_macro_with_attribute() {
        let buf = cocaine_log!(__test # "test", 1, "nginx/1.6 configured"; {
            config: "/etc/nginx/nginx.conf",
        }).unwrap();
        let expected = Value::Array(vec![
            Value::from(1),
            Value::from("test"),
            Value::from("nginx/1.6 configured"),
            Value::Array(vec![
                Value::Array(vec![
                    Value::from("config"),
                    Value::from("/etc/nginx/nginx.conf")
                ])
            ])
        ]);
        assert_eq!(expected, rmpv::decode::read_value(&mut &buf[..]).unwrap());
    }

    #[test]
    fn test_macro_with_attributes() {
        let buf = cocaine_log!(__test # "test", 1, "nginx/1.6 configured"; {
            config: "/etc/nginx/nginx.conf",
            elapsed: 42.15,
        }).unwrap();
        let expected = Value::Array(vec![
            Value::from(1),
            Value::from("test"),
            Value::from("nginx/1.6 configured"),
            Value::Array(vec![
                Value::Array(vec![
                    Value::from("config"),
                    Value::from("/etc/nginx/nginx.conf")
                ]),
                Value::Array(vec![
                    Value::from("elapsed"),
                    Value::from(42.15)
                ])
            ])
        ]);
        assert_eq!(expected, rmpv::decode::read_value(&mut &buf[..]).unwrap());
    }

    #[test]
    fn test_macro_with_args_and_attributes() {
        let buf = cocaine_log!(__test # "test", 1, "file does not exist: {}", "/var/www/favicon.ico"; {
            path: "/",
            cache: true,
            method: "GET",
            version: 1.1,
            protocol: "HTTP",
        }).unwrap();
        let expected = Value::Array(vec![
            Value::from(1),
            Value::from("test"),
            Value::from("file does not exist: /var/www/favicon.ico"),
            Value::Array(vec![
                Value::Array(vec![
                    Value::from("path"),
                    Value::from("/")
                ]),
                Value::Array(vec![
                    Value::from("cache"),
                    Value::from(true)
                ]),
                Value::Array(vec![
                    Value::from("method"),
                    Value::from("GET")
                ]),
                Value::Array(vec![
                    Value::from("version"),
                    Value::from(1.1)
                ]),
                Value::Array(vec![
                    Value::from("protocol"),
                    Value::from("HTTP")
                ])
            ])
        ]);
        assert_eq!(expected, rmpv::decode::read_value(&mut &buf[..]).unwrap());
    }
}