Skip to content

Commit 2581dc0

Browse files
committed
feat: 📈 intensive tracing log
1 parent dc93a95 commit 2581dc0

File tree

11 files changed

+85
-52
lines changed

11 files changed

+85
-52
lines changed

backend/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ hickory-resolver = "0.24.0"
3030
crossbeam-queue = "0.3.8"
3131
dashmap = "5.5.3"
3232
tracing-opentelemetry = "0.22.0"
33+
# a lot of opentelemetry dependencies
3334
opentelemetry_sdk = { version = "0.21.1", features = ["rt-tokio"] }
3435
opentelemetry = "0.21.0"
3536
opentelemetry-stdout = { version = "0.2.0", features = ["metrics"] }
@@ -46,7 +47,7 @@ features = ["json"]
4647

4748
[dependencies.tracing]
4849
version = "0.1.40"
49-
features = ["async-await", "log"]
50+
features = ["async-await", "log", "release_max_level_debug"]
5051

5152
[dependencies.tokio]
5253
version = "1.34.0"

backend/src/controller/crypto.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use ring::{
33
signature::{self, KeyPair},
44
};
55
use serde::{de::DeserializeOwned, Serialize};
6+
use tracing::Span;
67

78
use crate::{init::config::GlobalConfig, report_internal};
89

@@ -46,8 +47,8 @@ impl From<HashValue> for Vec<u8> {
4647
}
4748

4849
impl CryptoController {
49-
#[tracing::instrument(level = "info")]
50-
pub fn new(config: &GlobalConfig) -> Self {
50+
#[tracing::instrument(parent=span,name="crypto_construct",level = "info",skip_all)]
51+
pub fn new(config: &GlobalConfig, span: &Span) -> Self {
5152
let rng = rand::SystemRandom::new();
5253
let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
5354
let signer = signature::Ed25519KeyPair::from_pkcs8(pkcs8_bytes.as_ref()).unwrap();

backend/src/controller/duplicate.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
11
use quick_cache::sync::Cache;
2+
use tracing::Span;
23
use uuid::Uuid;
34

45
pub struct DupController {
56
#[cfg(feature = "single-instance")]
67
dups: Cache<(i32, Uuid), i32>,
78
}
89

9-
impl Default for DupController {
10-
fn default() -> Self {
11-
log::debug!("Setup DupController");
10+
impl DupController {
11+
#[tracing::instrument(parent=span, name="duplicate_construct",level = "info",skip_all)]
12+
pub fn new(span: &Span) -> Self {
1213
Self {
1314
#[cfg(feature = "single-instance")]
1415
dups: Cache::new(300),
1516
}
1617
}
17-
}
18-
19-
impl DupController {
2018
pub fn store(&self, user_id: i32, uuid: Uuid, result: i32) {
2119
#[cfg(feature = "single-instance")]
2220
self.dups.insert((user_id, uuid), result);

backend/src/controller/judger/mod.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use sea_orm::{ActiveModelTrait, ActiveValue, EntityTrait, QueryOrder};
99
use thiserror::Error;
1010
use tokio_stream::StreamExt;
1111
use tonic::Status;
12+
use tracing::{instrument, span, Instrument, Level, Span};
1213
use uuid::Uuid;
1314

1415
use crate::{
@@ -113,16 +114,18 @@ impl From<JudgeResult> for SubmitStatus {
113114
}
114115
}
115116

116-
pub struct SubmitController {
117+
pub struct JudgerController {
117118
router: Arc<Router>,
118119
pubsub: Arc<PubSub<Result<SubmitStatus, Status>, i32>>,
119120
limiter: Arc<RateLimiter>,
120121
}
121122

122-
impl SubmitController {
123-
pub async fn new(config: &GlobalConfig) -> Result<Self, Error> {
124-
Ok(SubmitController {
125-
router: Router::new(config.judger.clone()).await?,
123+
impl JudgerController {
124+
#[tracing::instrument(parent=span, name="judger_construct",level = "info",skip_all)]
125+
pub async fn new(config: &GlobalConfig, span: &Span) -> Result<Self, Error> {
126+
let router = Router::new(config.judger.clone(), span).await?;
127+
Ok(JudgerController {
128+
router,
126129
pubsub: Arc::new(PubSub::default()),
127130
limiter: Arc::new(
128131
RateLimiter::builder()
@@ -134,11 +137,13 @@ impl SubmitController {
134137
),
135138
})
136139
}
140+
#[instrument(skip(ps_guard, stream, model, scores))]
137141
async fn stream(
138142
ps_guard: PubGuard<Result<SubmitStatus, Status>, i32>,
139143
mut stream: tonic::Streaming<JudgeResponse>,
140144
mut model: submit::ActiveModel,
141145
mut scores: Vec<u32>,
146+
submit_id: i32,
142147
) {
143148
let mut result = 0;
144149
let mut running_case = 0;
@@ -252,7 +257,13 @@ impl SubmitController {
252257

253258
conn.report_success();
254259

255-
tokio::spawn(Self::stream(tx, res.into_inner(), submit_model, scores));
260+
tokio::spawn(Self::stream(
261+
tx,
262+
res.into_inner(),
263+
submit_model,
264+
scores,
265+
submit_id,
266+
));
256267

257268
Ok(submit_id)
258269
}

backend/src/controller/judger/route/mod.rs

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::{
1414
use crossbeam_queue::SegQueue;
1515
use dashmap::{DashMap, DashSet};
1616
use tonic::{service::Interceptor, *};
17+
use tracing::{instrument, span, Instrument, Level, Span};
1718
use uuid::Uuid;
1819

1920
use crate::{
@@ -106,21 +107,23 @@ async fn discover<I: Routable + Send>(
106107
config: JudgerConfig,
107108
router: Weak<Router>,
108109
) -> Result<(), Error> {
109-
let span = tracing::span!(
110-
tracing::Level::DEBUG,
111-
"service discover",
112-
name = config.name
113-
);
114-
let mut instance = I::new(config)?;
110+
let mut instance = I::new(config.clone())?;
111+
let span = span!(Level::INFO, "service_discover", config_name = config.name);
115112
loop {
116-
match instance.discover().await {
113+
match instance
114+
.discover()
115+
.instrument(span!(parent:span.clone(),Level::DEBUG, "try advance"))
116+
.in_current_span()
117+
.await
118+
{
117119
RouteStatus::NewConnection(detail) => {
118-
log::info!("new upstream found: {}", detail.uri);
120+
let span =
121+
span!(parent:span.clone(),Level::DEBUG,"upstream_connect",uri=detail.uri);
119122
let router = match router.upgrade() {
120123
Some(x) => x,
121124
None => break,
122125
};
123-
let (upstream, langs) = Upstream::new(detail).await?;
126+
let (upstream, langs) = Upstream::new(detail).in_current_span().await?;
124127
for (uuid, lang) in langs.into_iter() {
125128
router.langs.insert(lang);
126129
loop {
@@ -136,14 +139,10 @@ async fn discover<I: Routable + Send>(
136139
}
137140
}
138141
}
139-
RouteStatus::Wait(dur) => {
140-
log::trace!("Service Discovery halt for {} seconds", dur.as_secs());
141-
tokio::time::sleep(dur).await
142-
}
142+
RouteStatus::Wait(dur) => tokio::time::sleep(dur).in_current_span().await,
143143
_ => break,
144144
}
145145
}
146-
drop(span);
147146
Ok(())
148147
}
149148

@@ -154,8 +153,8 @@ pub struct Router {
154153

155154
impl Router {
156155
// skip because config contain basic auth secret
157-
#[tracing::instrument(level = "debug", skip_all)]
158-
pub async fn new(config: Vec<JudgerConfig>) -> Result<Arc<Self>, Error> {
156+
#[instrument(name="router_construct",level = "info",skip_all, follows_from = [span])]
157+
pub async fn new(config: Vec<JudgerConfig>, span: &Span) -> Result<Arc<Self>, Error> {
159158
let self_ = Arc::new(Self {
160159
routing_table: DashMap::default(),
161160
langs: DashSet::default(),
@@ -206,7 +205,7 @@ pub struct Upstream {
206205
healthy: AtomicIsize,
207206
clients: SegQueue<JudgerIntercept>,
208207
connection: ConnectionDetail,
209-
_live_span: tracing::Span,
208+
// live_span: tracing::span::EnteredSpan,
210209
}
211210

212211
impl Upstream {
@@ -227,8 +226,6 @@ impl Upstream {
227226
result.push((uuid, lang));
228227
}
229228

230-
let live_span = tracing::span!(tracing::Level::INFO, "judger livetime", uri = detail.uri);
231-
232229
let clients = SegQueue::default();
233230
clients.push(client);
234231

@@ -237,7 +234,6 @@ impl Upstream {
237234
healthy: AtomicIsize::new(HEALTHY_THRESHOLD),
238235
clients,
239236
connection: detail,
240-
_live_span: live_span,
241237
}),
242238
result,
243239
))

backend/src/controller/token.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use sea_orm::{
77
};
88
use std::sync::Arc;
99
use tokio::time;
10-
use tracing::instrument;
10+
use tracing::{instrument, Span};
1111

1212
use crate::{init::db::DB, report_internal};
1313

@@ -65,7 +65,8 @@ pub struct TokenController {
6565
}
6666

6767
impl TokenController {
68-
pub fn new() -> Arc<Self> {
68+
#[tracing::instrument(parent = span,name="token_construct",level = "info",skip_all)]
69+
pub fn new(span: &Span) -> Arc<Self> {
6970
log::debug!("Setup TokenController");
7071
#[cfg(feature = "single-instance")]
7172
let cache = Cache::new(300);

backend/src/endpoint/education.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,10 @@ use entity::{education::*, *};
88

99
impl Filter for Entity {
1010
fn read_filter<S: QueryFilter + Send>(query: S, auth: &Auth) -> Result<S, Error> {
11-
let (user_id, perm) = auth.ok_or_default()?;
12-
if perm.can_root() {
13-
return Ok(query);
14-
}
15-
if perm.can_manage_education() {
16-
return Ok(query.filter(education::Column::UserId.eq(user_id)));
11+
if let Some(perm) = auth.user_perm() {
12+
if perm.can_root() || perm.can_manage_education() {
13+
return Ok(query);
14+
}
1715
}
1816
Err(Error::Unauthenticated)
1917
}

backend/src/endpoint/util/pagination.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::marker::PhantomData;
33
use ::entity::*;
44
use sea_orm::*;
55
use serde::{Deserialize, Serialize};
6+
use tracing::instrument;
67

78
use crate::{grpc::backend::SortBy, init::db::DB};
89

@@ -361,13 +362,15 @@ where
361362
}
362363

363364
impl<E: PagerTrait> Pager<E> {
365+
#[instrument(level = "debug")]
364366
pub fn sort_search(sort: SortBy, reverse: bool) -> Self {
365367
Self {
366368
ppk: None,
367369
sort: SearchDep::Column(sort, reverse),
368370
_entity: PhantomData,
369371
}
370372
}
373+
#[instrument(level = "debug")]
371374
pub fn text_search(sort: String) -> Self {
372375
Self {
373376
ppk: None,

backend/src/init/logger.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,19 @@ fn init_tracing_subscriber(level: Level) -> OtelGuard {
107107
.with(MetricsLayer::new(meter_provider.clone()))
108108
.with(OpenTelemetryLayer::new(init_tracer()))
109109
.init();
110+
111+
std::panic::set_hook(Box::new(|panic| {
112+
if let Some(location) = panic.location() {
113+
tracing::error!(
114+
message = %panic,
115+
panic.file = location.file(),
116+
panic.line = location.line(),
117+
panic.column = location.column(),
118+
);
119+
} else {
120+
tracing::error!(message = %panic);
121+
}
122+
}));
110123

111124
OtelGuard { meter_provider }
112125
}

backend/src/server.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::sync::Arc;
22

33
use tokio::fs;
44
use tonic::transport;
5+
use tracing::{instrument, span, Instrument, Level};
56

67
use crate::{
78
controller::*,
@@ -22,7 +23,7 @@ const MAX_FRAME_SIZE: u32 = 1024 * 1024 * 8;
2223

2324
pub struct Server {
2425
pub token: Arc<token::TokenController>,
25-
pub submit: judger::SubmitController,
26+
pub submit: judger::JudgerController,
2627
pub dup: duplicate::DupController,
2728
pub crypto: crypto::CryptoController,
2829
config: GlobalConfig,
@@ -34,25 +35,35 @@ impl Server {
3435
pub async fn new() -> Arc<Self> {
3536
let config = config::init().await;
3637

37-
init::db::init(&config).await;
3838
let otp_guard = logger::init(&config);
3939

40-
log::info!("Loading TLS certificate...");
40+
let span = span!(Level::INFO, "construct_server");
41+
42+
init::db::init(&config)
43+
.instrument(span!(parent:span.clone(),Level::INFO,"construct_database"))
44+
.await;
45+
46+
tracing::info!("Loading TLS certificate...");
4147
let cert = fs::read_to_string(&config.grpc.public_pem)
48+
.instrument(span!(parent:span.clone(),Level::INFO,"load_tls"))
4249
.await
4350
.expect("public key.pem not found");
4451
let key = fs::read_to_string(&config.grpc.private_pem)
52+
.instrument(span!(parent:span.clone(),Level::INFO,"load_tls"))
4553
.await
4654
.expect("privite key.pem not found");
55+
4756
let identity = transport::Identity::from_pem(cert, key);
4857

49-
log::info!("Constructing server...");
58+
tracing::info!("Constructing server...");
59+
60+
let submit = judger::JudgerController::new(&config, &span).await.unwrap();
5061

5162
Arc::new(Server {
52-
token: token::TokenController::new(),
53-
submit: judger::SubmitController::new(&config).await.unwrap(),
54-
dup: duplicate::DupController::default(),
55-
crypto: crypto::CryptoController::new(&config),
63+
token: token::TokenController::new(&span),
64+
submit: submit,
65+
dup: duplicate::DupController::new(&span),
66+
crypto: crypto::CryptoController::new(&config, &span),
5667
config,
5768
identity,
5869
_otp_guard: otp_guard,

judger/src/init/logger.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ pub fn init() {
1414
_ => Level::Info,
1515
};
1616

17-
simple_logger::init_with_level(level).unwrap();
17+
simple_logger::init_with_level(level).ok();
1818
}

0 commit comments

Comments
 (0)