Skip to content

Commit

Permalink
riir
Browse files Browse the repository at this point in the history
  • Loading branch information
foriequal0 committed Jul 31, 2024
1 parent 277beff commit 5d31d7d
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 32 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ uuid = { version = "1.10.0", features = ["v4"] }

[dev-dependencies]
tempfile = "3.10.1"
serde_yaml = "0.9.34+deprecated"
serde_yaml = "0.9.34-deprecated"
local-ip-address = "0.6.1"
base64 = "0.22.1"
rcgen = "0.13.1"
Expand Down
2 changes: 1 addition & 1 deletion src/webhooks/log_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ where
}

fn call(&mut self, request: Request) -> Self::Future {
trace!("{:?}", request);
trace!(?request);
self.service.call(request)
}
}
Expand Down
35 changes: 17 additions & 18 deletions tests/testutils/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::collections::{BTreeMap, HashSet};
use std::future::Future;
use std::io::Write;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::{Arc, Mutex};

use eyre::{Context, Result};
Expand All @@ -14,14 +13,16 @@ use kube::{Api, Client, Config};
use rand::Rng;
use tempfile::NamedTempFile;
use tokio::task::JoinError;
use tracing_subscriber::filter::Directive;
use tracing::dispatcher::DefaultGuard;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::EnvFilter;
use uuid::Uuid;

use pod_graceful_drain::{ApiResolver, LoadBalancingConfig, Shutdown};

use crate::testutils::run_command::{get_command_output, run_command, CommandParams};
use crate::testutils::run_command::{
get_command_output, run_command, run_command_before_logger, CommandParams,
};

const DEFAULT_KIND_IMAGE: &str = "kindest/node:v1.30.0";
const DEFAULT_TEST_CLUSTER_NAME: &str = "test-pgd";
Expand Down Expand Up @@ -63,6 +64,7 @@ where
Fut: Future + Send,
Fut::Output: Send + 'static,
{
let _ = set_default_test_logger();
let kind_cluster =
std::env::var("KIND_CLUSTER").unwrap_or(DEFAULT_TEST_CLUSTER_NAME.to_owned());
let result = within_random_namespace_with_cluster(&kind_cluster, f).await;
Expand All @@ -78,6 +80,7 @@ where
Fut: Future + Send,
Fut::Output: Send + 'static,
{
let _ = set_default_test_logger();
let random_cluster_name = format!(
"{DEFAULT_TEST_CLUSTER_NAME}-{}",
rand::thread_rng().gen_range(0..100000)
Expand Down Expand Up @@ -160,21 +163,7 @@ where

let result = tokio::spawn({
let context = context.clone();
async move {
let _default_guard = tracing::subscriber::set_default({
let filter = EnvFilter::builder()
.with_default_directive(
Directive::from_str("pod_graceful_drain=trace").unwrap(),
)
.from_env_lossy();

tracing_subscriber::registry()
.with(filter)
.with(tracing_subscriber::fmt::layer().with_test_writer())
});

f(context).await
}
async move { f(context).await }
})
.await;

Expand Down Expand Up @@ -269,3 +258,13 @@ async fn delete_namespace(client: &Client, ns: &str) -> Result<()> {
let _ns = api.delete(ns, &DeleteParams::default()).await?;
Ok(())
}

fn set_default_test_logger() -> DefaultGuard {
tracing::subscriber::set_default({
let filter = EnvFilter::new("pod_graceful_drain=trace,test=trace");

tracing_subscriber::registry()
.with(filter)
.with(tracing_subscriber::fmt::layer().with_test_writer())
})
}
35 changes: 27 additions & 8 deletions tests/testutils/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::process::{Command, Output, Stdio};

use eyre::{eyre, Context, Result};
use tokio::task::spawn_blocking;
use tracing::{span, trace, Level};

#[derive(Clone)]
pub struct CommandParams<'a> {
Expand Down Expand Up @@ -49,7 +50,10 @@ impl Display for CommandParams<'_> {
}

pub async fn run_command(params: &CommandParams<'_>) -> Result<()> {
println!("$> {params}");
let span = span!(target: "test", Level::ERROR, "command", %params);
assert!(!span.is_disabled(), "logger should be set");

trace!(target: "test", parent: &span, "start");

let mut command = Command::new(params.command);
command.args(params.config_args);
Expand All @@ -61,6 +65,7 @@ pub async fn run_command(params: &CommandParams<'_>) -> Result<()> {
}

let output = spawn_blocking({
let span = span.clone();
let params = params.clone();
move || -> Result<Output> {
let mut child = command.spawn()?;
Expand All @@ -72,14 +77,21 @@ pub async fn run_command(params: &CommandParams<'_>) -> Result<()> {

let stdout = child.stdout.take().expect("piped");
let stderr = child.stderr.take().expect("piped");
spawn_blocking(move || {
for line in BufReader::new(stdout).lines() {
println!("{}", line.unwrap());

spawn_blocking({
let span = span.clone();
move || {
for line in BufReader::new(stdout).lines() {
trace!(target: "test", parent: &span, "{}", line.unwrap());
}
}
});
spawn_blocking(move || {
for line in BufReader::new(stderr).lines() {
eprintln!("{}", line.unwrap());
spawn_blocking({
let span = span.clone();
move || {
for line in BufReader::new(stderr).lines() {
trace!(target: "test", parent: &span, stream="stderr", "{}", line.unwrap());
}
}
});

Expand All @@ -89,6 +101,8 @@ pub async fn run_command(params: &CommandParams<'_>) -> Result<()> {
.await
.context(format!("command: {params}"))??;

trace!(target: "test", parent: &span, "exited ({status})", status = output.status);

if !output.status.success() {
return Err(eyre!("Command({params}) ({:?}):", output.status));
}
Expand All @@ -97,7 +111,10 @@ pub async fn run_command(params: &CommandParams<'_>) -> Result<()> {
}

pub async fn get_command_output(params: &CommandParams<'_>) -> Result<Vec<u8>> {
println!("$> {params}");
let span = span!(target: "test", Level::ERROR, "command", %params);
assert!(!span.is_disabled(), "logger should be set");

trace!(target: "test", parent: &span, "start");

let mut command = Command::new(params.command);
command.args(params.config_args);
Expand All @@ -124,6 +141,8 @@ pub async fn get_command_output(params: &CommandParams<'_>) -> Result<Vec<u8>> {
.await
.context(format!("command: {params}"))??;

trace!(target: "test", parent: &span, "exited ({status})", status = output.status);

if !output.status.success() {
stdout().write_all(&output.stdout).unwrap();
stderr().write_all(&output.stderr).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions tests/webhooks_drain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ webhooks:
apiVersions: [v1]
operations: [DELETE]
resources: [pods]
failurePolicy: Fail
failurePolicy: Ignore
sideEffects: NoneOnDryRun
timeoutSeconds: 30
timeoutSeconds: 10
namespaceSelector:
matchLabels:
name: {namespace}"#,
Expand All @@ -117,9 +117,9 @@ webhooks:
apiVersions: [v1]
operations: [CREATE]
resources: [pods/eviction]
failurePolicy: Fail
failurePolicy: Ignore
sideEffects: NoneOnDryRun
timeoutSeconds: 30
timeoutSeconds: 10
namespaceSelector:
matchLabels:
name: {namespace}"#,
Expand Down

0 comments on commit 5d31d7d

Please sign in to comment.