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

Embedded Metrics Logging #26

Merged
merged 1 commit into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
extern crate libc;
mod log;
use lazy_static::lazy_static;
use libc::c_char;
use std::collections::HashMap;
Expand Down Expand Up @@ -27,7 +28,7 @@ redhook::hook! {
}
}
if DEBUG {
println!("[crypteia] libcrypteia: initialized using LD_PRELOAD");
log::cloudwatch_metric("lib", "initialized", false, None);
}
});
let env_value = redhook::real!(getenv)(name);
Expand Down Expand Up @@ -73,7 +74,7 @@ fn is_env_file() -> bool {
let boo_value = metadata(ENV_FILE).is_ok();
unsafe {
if DEBUG {
println!("[crypteia] libcrypteia: is_env_file() -> {}", boo_value);
log::cloudwatch_metric("lib", "is_env_file", false, None);
}
}
boo_value
Expand All @@ -96,7 +97,7 @@ fn read_env_file() {
});
unsafe {
if DEBUG {
println!("[crypteia] libcrypteia: read_env_file()");
log::cloudwatch_metric("lib", "read_env_file", false, None);
}
}
delete_file();
Expand All @@ -107,7 +108,7 @@ fn delete_file() {
remove_file(ENV_FILE).unwrap();
unsafe {
if DEBUG {
println!("[crypteia] libcrypteia: delete_file()");
log::cloudwatch_metric("lib", "delete_file", false, None);
}
}
}
39 changes: 39 additions & 0 deletions src/log.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use serde_json::json;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

pub fn cloudwatch_metric(dimension: &str, name: &str, error: bool, error_message: Option<String>) {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
.to_string()
.parse::<u64>()
.unwrap();
let metric = serde_json::to_string(&json!(
{
"_aws": {
"Timestamp": timestamp,
"CloudWatchMetrics": [
{
"Namespace": "Crypteia",
"Dimensions": [["All", dimension]],
"Metrics": [
{ "Name": name, "Unit": "Count"}
]
}
]
},
"All": "all",
dimension: dimension,
name: 1,
"ErrorMessage": error_message.unwrap_or("".to_string()),
}
))
.unwrap();
if error {
eprintln!("{}", metric);
} else {
println!("{}", metric);
}
}
7 changes: 4 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod log;
mod ssm;
use lambda_extension::{service_fn, Error, LambdaEvent, NextEvent};
use std::collections::HashMap;
Expand All @@ -8,10 +9,10 @@ const ENV_FILE: &str = "/tmp/crypteia.json";

#[tokio::main]
async fn main() -> Result<(), Error> {
println!("[crypteia] main: Init");
log::cloudwatch_metric("main", "initialized", false, None);
let env_vars: HashMap<String, String> = std::env::vars().collect();
let env_map = ssm::get_envs(env_vars).await.unwrap();
println!("[crypteia] main: Fetched environment variables");
log::cloudwatch_metric("main", "fetched", false, None);
write_envs_to_tmp_json(env_map);
let func = service_fn(parameters_extension);
lambda_extension::run(func).await
Expand All @@ -20,7 +21,7 @@ async fn main() -> Result<(), Error> {
async fn parameters_extension(event: LambdaEvent) -> Result<(), Error> {
match event.next {
NextEvent::Shutdown(_e) => {
println!("[crypteia] main: Shutdown");
log::cloudwatch_metric("main", "shutdown", false, None);
}
NextEvent::Invoke(_e) => {}
}
Expand Down
27 changes: 19 additions & 8 deletions src/ssm.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::log;
use anyhow::Result;
use futures::future::join_all;
use std::collections::HashMap;
Expand Down Expand Up @@ -30,9 +31,9 @@ pub async fn get_envs(env_vars: HashMap<String, String>) -> Result<HashMap<Strin
results.insert(key, value);
});
}
Err(error) => eprintln!("[crypteia] ssm: Parameter error {err}", err = error),
Err(error) => log::cloudwatch_metric("ssm", "error", true, Some(error.to_string())),
},
Err(error) => eprintln!("[crypteia] ssm: JoinError {err}", err = error),
Err(error) => log::cloudwatch_metric("ssm", "error", true, Some(error.to_string())),
}
}
Ok(results)
Expand All @@ -57,9 +58,14 @@ async fn ssm_get_parameter(
}
}
Err(error) => {
eprintln!(
"[crypteia] ssm: Error calling ssm:GetParameter. Environment variable: {name} Path: {path} Error: {err}",
err = error
log::cloudwatch_metric(
"ssm",
"error",
true,
Some(format!(
"Error calling ssm:GetParameter. Environment variable: {} Path: {} Error: {}",
name, path, error
)),
);
}
}
Expand Down Expand Up @@ -100,9 +106,14 @@ async fn ssm_get_parameters_by_path(
token = response.next_token;
}
Err(error) => {
eprintln!(
"[crypteia] ssm: Error calling ssm:GetParametersByPath. Environment variable: {name} Path: {path} Error: {err}",
err = error
log::cloudwatch_metric(
"ssm",
"error",
true,
Some(format!(
"Error calling ssm:GetParametersByPath. Environment variable: {} Path: {} Error: {}",
name, path, error
)),
);
break;
}
Expand Down