Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhancement(remap): Add to_syslog_level function for parsing Syslog levels into strings #5503

Merged
merged 16 commits into from
Dec 21, 2020
40 changes: 40 additions & 0 deletions docs/reference/remap/to_level.cue
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package metadata

remap: functions: to_level: {
arguments: [
{
name: "severity"
description: "The integer severity level."
required: true
type: ["integer"]
},
]
return: ["string"]
category: "parse"
description: """
Converts a Syslog [severity level](\(urls.syslog_levels)) into its corresponding keyword,
i.e. 0 into `"emerg"`, 1 into `"alert", etc.
"""
examples: [
{
title: "Success"
input: {
severity: "5"
}
source: ".log_level = to_level(.severity)"
output: {
level: "notice"
}
},
{
title: "Error"
input: {
severity: "1337"
}
source: ".log_level = to_severity(.severity)"
output: {
error: remap.errors.ParseError
}
},
]
}
1 change: 1 addition & 0 deletions docs/reference/urls.cue
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ urls: {
syslog_3164: "https://tools.ietf.org/html/rfc3164"
syslog_5424: "https://tools.ietf.org/html/rfc5424"
syslog_6587: "https://tools.ietf.org/html/rfc6587"
syslog_levels: "https://en.wikipedia.org/wiki/Syslog#Severity_level"
systemd: "https://systemd.io/"
systemd_limit_resources: "https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html"
systemd_resolved: "https://wiki.archlinux.org/index.php/Systemd-resolved"
Expand Down
2 changes: 2 additions & 0 deletions lib/remap-functions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ default = [
"to_bool",
"to_float",
"to_int",
"to_level",
"to_string",
"to_timestamp",
"tokenize",
Expand Down Expand Up @@ -135,6 +136,7 @@ strip_whitespace = []
to_bool = ["shared/conversion"]
to_float = ["shared/conversion"]
to_int = ["shared/conversion"]
to_level = []
lucperkins marked this conversation as resolved.
Show resolved Hide resolved
to_string = []
to_timestamp = ["chrono"]
tokenize = ["shared/tokenize"]
Expand Down
6 changes: 6 additions & 0 deletions lib/remap-functions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ mod to_bool;
mod to_float;
#[cfg(feature = "to_int")]
mod to_int;
#[cfg(feature = "to_level")]
mod to_level;
#[cfg(feature = "to_string")]
mod to_string;
#[cfg(feature = "to_timestamp")]
Expand Down Expand Up @@ -199,6 +201,8 @@ pub use to_bool::ToBool;
pub use to_float::ToFloat;
#[cfg(feature = "to_int")]
pub use to_int::ToInt;
#[cfg(feature = "to_level")]
pub use to_level::ToLevel;
#[cfg(feature = "to_string")]
pub use to_string::ToString;
#[cfg(feature = "to_timestamp")]
Expand Down Expand Up @@ -306,6 +310,8 @@ pub fn all() -> Vec<Box<dyn remap::Function>> {
Box::new(ToFloat),
#[cfg(feature = "to_int")]
Box::new(ToInt),
#[cfg(feature = "to_level")]
Box::new(ToLevel),
#[cfg(feature = "to_string")]
Box::new(ToString),
#[cfg(feature = "to_timestamp")]
Expand Down
151 changes: 151 additions & 0 deletions lib/remap-functions/src/to_level.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use remap::prelude::*;

#[derive(Clone, Copy, Debug)]
pub struct ToLevel;

impl Function for ToLevel {
fn identifier(&self) -> &'static str {
"to_level"
}

fn parameters(&self) -> &'static [Parameter] {
&[Parameter {
keyword: "value",
accepts: |v| matches!(v, Value::Integer(_)),
required: true,
}]
}

fn compile(&self, mut arguments: ArgumentList) -> Result<Box<dyn Expression>> {
let value = arguments.required("value")?.boxed();

Ok(Box::new(ToLevelFn { value }))
}
}

#[derive(Debug, Clone)]
struct ToLevelFn {
value: Box<dyn Expression>,
}

impl Expression for ToLevelFn {
fn execute(&self, state: &mut state::Program, object: &mut dyn Object) -> Result<Value> {
let value = self.value.execute(state, object)?.try_integer()?;

// Severity levels: https://en.wikipedia.org/wiki/Syslog#Severity_level
let level = match value {
0 => Ok("emerg"),
1 => Ok("alert"),
2 => Ok("crit"),
3 => Ok("err"),
4 => Ok("warning"),
5 => Ok("notice"),
6 => Ok("info"),
7 => Ok("debug"),
_ => Err(Error::from(format!("severity level {} not valid", value))),
};

match level {
Ok(level) => Ok(Value::from(level)),
Err(e) => Err(e),
}
}

fn type_def(&self, state: &state::Compiler) -> TypeDef {
use value::Kind;

self.value
.type_def(state)
.fallible_unless(Kind::Integer)
.with_constraint(Kind::Bytes)
}
}

#[cfg(test)]
mod tests {
use super::*;
use value::Kind;

test_type_def![
value_integer_non_fallible {
expr: |_| ToLevelFn {
value: Literal::from(3).boxed(),
},
def: TypeDef {
fallible: false,
kind: Kind::Bytes,
..Default::default()
},
}

value_non_integer_fallible {
expr: |_| ToLevelFn {
value: Literal::from("foo").boxed(),
},
def: TypeDef {
fallible: true,
kind: Kind::Bytes,
..Default::default()
},
}
];

test_function![
to_level => ToLevel;

emergency {
args: func_args![value: value!(0)],
want: Ok(value!("emerg")),
}

alert {
args: func_args![value: value!(1)],
want: Ok(value!("alert")),
}

critical {
args: func_args![value: value!(2)],
want: Ok(value!("crit")),
}

error {
args: func_args![value: value!(3)],
want: Ok(value!("err")),
}

warning {
args: func_args![value: value!(4)],
want: Ok(value!("warning")),
}

notice {
args: func_args![value: value!(5)],
want: Ok(value!("notice")),
}

informational {
args: func_args![value: value!(6)],
want: Ok(value!("info")),
}

debug {
args: func_args![value: value!(7)],
want: Ok(value!("debug")),
}

invalid_severity_next_int {
args: func_args![value: value!(8)],
want: Err("function call error: severity level 8 not valid"),
}

invalid_severity_larger_int {
args: func_args![value: value!(475)],
want: Err("function call error: severity level 475 not valid"),
}

invalid_severity_negative_int {
args: func_args![value: value!(-1)],
want: Err("function call error: severity level -1 not valid"),
}
];
}