Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Facilitate tracing from WASM #5826

Closed
wants to merge 91 commits into from
Closed
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
62f4df9
Add span recording to tracing implementation
mattrutherford Apr 27, 2020
e5aa529
Add tracing proxy
mattrutherford Apr 28, 2020
e71eb09
switch to rustc_hash::FxHashMap
mattrutherford Apr 29, 2020
db69268
Replace lazy_static and hashmap with thread_local and vec.
mattrutherford Apr 29, 2020
b43015f
fix marking valid span as invalid while removing invalid spans
mattrutherford Apr 29, 2020
dba7d55
refactor, add wasm_tracing module in `support`
mattrutherford May 6, 2020
5e86ef6
update registered spans
mattrutherford May 6, 2020
35706ca
tidy up
mattrutherford May 6, 2020
1388002
typos
mattrutherford May 6, 2020
41964e7
refactor
mattrutherford May 6, 2020
ad81d3b
update flag name to signal lost trace - `is_valid_trace`
mattrutherford May 6, 2020
2cb66bf
update flag name to signal lost trace - `is_valid_trace`
mattrutherford May 6, 2020
03b7b6e
update docs
mattrutherford May 6, 2020
16b018c
update docs
mattrutherford May 6, 2020
d2af83d
Use tracing Field recording to store the actual `name` and `target`
mattrutherford May 7, 2020
9f8baf2
fix debug log in subscriber + small refactor
mattrutherford May 7, 2020
1199f36
add tests
mattrutherford May 11, 2020
0c61f79
handle misuse in case trying to exit span not held
mattrutherford May 11, 2020
8061da5
Implement filter for wasm traces, simplify field recording for primit…
mattrutherford May 11, 2020
2097aca
remove superfluous warning
mattrutherford May 11, 2020
1ef18e6
update docs
mattrutherford May 11, 2020
60e0b60
Merge branch 'master' into mr-sp-tracing
mattrutherford May 11, 2020
cd8bed8
Merge branch 'master' into mr-sp-tracing
mattrutherford May 12, 2020
460d24d
Update primitives/tracing/src/proxy.rs
mattrutherford May 13, 2020
85bdbe0
Apply suggestions from code review
mattrutherford May 13, 2020
b9d1fdf
update docs, apply suggestions
mattrutherford May 14, 2020
b66bb33
move Proxy from thread_local to `Extension`, rename macro
mattrutherford May 14, 2020
afa511d
fix test
mattrutherford May 15, 2020
93a03a8
unify native & wasm span macro calls
mattrutherford May 15, 2020
2126d8e
implement wasm tracing control facility in primitives and frame
mattrutherford May 15, 2020
0d48517
add cli flag `--wasm-tracing`
mattrutherford May 15, 2020
e01ae89
fix
mattrutherford May 15, 2020
2db5f89
switch to `Option<u4>` (possible performance degradation), switch
mattrutherford May 15, 2020
c9c7e9c
performance improvement using u64 vs Option<u64>
mattrutherford May 15, 2020
e3bdb79
performance improvement moving concat to client
mattrutherford May 15, 2020
10a07a6
update docs
mattrutherford May 18, 2020
2b73ed7
Update client/cli/src/params/import_params.rs
mattrutherford May 18, 2020
cff0aa2
performance improvement
mattrutherford May 18, 2020
27c8a8f
Merge remote-tracking branch 'origin/mr-sp-tracing' into mr-sp-tracing
mattrutherford May 18, 2020
70e6315
Revert "performance improvement"
mattrutherford May 18, 2020
dc335e9
small refactor
mattrutherford May 18, 2020
955fa15
formatting
mattrutherford May 18, 2020
cd563c3
bump impl_version
mattrutherford May 18, 2020
1bc601f
Update client/cli/src/config.rs
mattrutherford May 19, 2020
691129d
Merge branch 'master' into mr-sp-tracing
mattrutherford May 19, 2020
e78dd7e
Merge branch 'master' into mr-sp-tracing
mattrutherford May 20, 2020
22bb40f
Merge branch 'master' into mr-sp-tracing
mattrutherford May 21, 2020
a63e6d5
update docs
mattrutherford May 21, 2020
88d3da1
Merge branch 'master' into mr-sp-tracing
mattrutherford May 28, 2020
7228358
small fixes, remove pub static
mattrutherford May 28, 2020
d735529
nit
mattrutherford May 29, 2020
de94f07
add integration tests and refactor Subscriber
mattrutherford Jun 1, 2020
8901340
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 1, 2020
179a515
tests
mattrutherford Jun 1, 2020
a2fbef3
revert formatting
mattrutherford Jun 1, 2020
74ec338
try fix test that works locally but not in CI
mattrutherford Jun 1, 2020
749657b
try fix test that works locally but not in CI
mattrutherford Jun 1, 2020
248f767
debug test that works locally but not in CI
mattrutherford Jun 1, 2020
19cf0f9
fix test that works locally but not in CI
mattrutherford Jun 1, 2020
ffe508a
remove pub visibility from bool in runtime
mattrutherford Jun 3, 2020
d5ba777
make TracingSpanGuard #[cfg(not(feature = "std"))], update docs, comm…
mattrutherford Jun 4, 2020
25e24c4
make TracingProxy drop implementation conditional on !empty state
mattrutherford Jun 4, 2020
da72fbd
add docs for TraceHandler
mattrutherford Jun 4, 2020
f7adde5
remove blank line
mattrutherford Jun 4, 2020
bed5bcb
update expect message
mattrutherford Jun 4, 2020
6f3602e
update tests
mattrutherford Jun 4, 2020
31b4cc1
merge master
mattrutherford Jun 4, 2020
1f016b9
rename cli option to tracing_enable_wasm
mattrutherford Jun 4, 2020
2a48d0a
rename cli option to tracing_enable_wasm
mattrutherford Jun 4, 2020
01693e0
fix
mattrutherford Jun 4, 2020
19d832c
merge master
mattrutherford Jun 9, 2020
a17775c
ensure wasm-tracing features are wasm only
mattrutherford Jun 9, 2020
2aa7c72
bump impl_version
mattrutherford Jun 9, 2020
3b7044d
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 9, 2020
bc9ec21
bump impl_version
mattrutherford Jun 9, 2020
32b8e36
add `"pallet-scheduler/std"` to `[features]` `std` in node/runtime
mattrutherford Jun 9, 2020
9835a01
refactor service to remove sp_tracing dependency
mattrutherford Jun 10, 2020
50e4c9c
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 10, 2020
8b16881
refactor: line width, trait bounds
mattrutherford Jun 10, 2020
068fd94
improve LogTraceHandler output
mattrutherford Jun 10, 2020
14a90ae
fix test
mattrutherford Jun 10, 2020
95b8832
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 10, 2020
b822794
improve tracing log output
mattrutherford Jun 11, 2020
157a639
Apply suggestions from code review
bkchr Jun 11, 2020
88c3d71
Apply suggestions from code review
mattrutherford Jun 15, 2020
4150780
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 15, 2020
07a0c56
Merge branch 'mr-sp-tracing' of github.com:paritytech/substrate into …
mattrutherford Jun 15, 2020
c36fc2a
swap wasm indication from trace name to a separate value
mattrutherford Jun 15, 2020
ca77a6a
Merge branch 'master' into mr-sp-tracing
mattrutherford Jun 15, 2020
d9ebb3b
Update client/tracing/src/lib.rs
bkchr Jun 15, 2020
1811e05
add docs
mattrutherford Jun 16, 2020
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
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions client/tracing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ targets = ["x86_64-unknown-linux-gnu"]
erased-serde = "0.3.9"
log = { version = "0.4.8" }
parking_lot = "0.10.0"
rustc-hash = "1.1.0"
serde = "1.0.101"
serde_json = "1.0.41"
slog = { version = "2.5.2", features = ["nested-values"] }
tracing-core = "0.1.7"

sc-telemetry = { version = "2.0.0-dev", path = "../telemetry" }
sp-tracing = { version = "2.0.0-dev", path = "../../primitives/tracing" }

[dev-dependencies]
tracing = "0.1.10"
92 changes: 61 additions & 31 deletions client/tracing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
//!
//! Currently we provide `Log` (default), `Telemetry` variants for `Receiver`

use std::collections::HashMap;
use rustc_hash::FxHashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
Expand All @@ -38,11 +38,13 @@ use tracing_core::{
Level,
metadata::Metadata,
span::{Attributes, Id, Record},
subscriber::Subscriber
subscriber::Subscriber,
};

use sc_telemetry::{telemetry, SUBSTRATE_INFO};

use sp_tracing::proxy::{WASM_NAME_KEY, WASM_TARGET_KEY, WASM_TRACE_IDENTIFIER};

/// Used to configure how to receive the metrics
#[derive(Debug, Clone)]
pub enum TracingReceiver {
Expand All @@ -61,8 +63,8 @@ impl Default for TracingReceiver {
#[derive(Debug)]
struct SpanDatum {
id: u64,
name: &'static str,
target: &'static str,
name: String,
target: String,
level: Level,
line: u32,
start_time: Instant,
Expand All @@ -71,23 +73,27 @@ struct SpanDatum {
}

#[derive(Clone, Debug)]
struct Visitor(Vec<(String, String)>);
struct Visitor(FxHashMap<String, String>);

impl Visit for Visitor {
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_debug(field, &value)
self.0.insert(field.name().to_string(), value.to_string());
}

fn record_u64(&mut self, field: &Field, value: u64) {
self.record_debug(field, &value)
self.0.insert(field.name().to_string(), value.to_string());
}

fn record_bool(&mut self, field: &Field, value: bool) {
self.record_debug(field, &value)
self.0.insert(field.name().to_string(), value.to_string());
}

fn record_str(&mut self, field: &Field, value: &str) {
self.0.insert(field.name().to_string(), value.to_owned());
}

fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.0.push((field.name().to_string(), format!("{:?}",value)));
self.0.insert(field.name().to_string(), format!("{:?}", value));
}
}

Expand All @@ -105,7 +111,7 @@ impl Serialize for Visitor {

impl fmt::Display for Visitor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let values = self.0.iter().map(|(k,v)| format!("{}={}",k,v)).collect::<Vec<String>>().join(", ");
let values = self.0.iter().map(|(k, v)| format!("{}={}", k, v)).collect::<Vec<String>>().join(", ");
write!(f, "{}", values)
}
}
Expand Down Expand Up @@ -136,7 +142,7 @@ pub struct ProfilingSubscriber {
next_id: AtomicU64,
targets: Vec<(String, Level)>,
receiver: TracingReceiver,
span_data: Mutex<HashMap<u64, SpanDatum>>,
span_data: Mutex<FxHashMap<u64, SpanDatum>>,
}

impl ProfilingSubscriber {
Expand All @@ -149,9 +155,20 @@ impl ProfilingSubscriber {
next_id: AtomicU64::new(1),
targets,
receiver,
span_data: Mutex::new(HashMap::new()),
span_data: Mutex::new(FxHashMap::default()),
}
}

fn check_target(&self, target: &str, level: &Level) -> bool {
for t in &self.targets {
if target.starts_with(t.0.as_str()) && level <= &t.1 {
log::debug!("Enabled target: {}, level: {}", target, level);
return true;
}
}
log::debug!("Disabled target: {}, level: {}", target, level);
false
}
}

// Default to TRACE if no level given or unable to parse Level
Expand All @@ -173,25 +190,24 @@ fn parse_target(s: &str) -> (String, Level) {

impl Subscriber for ProfilingSubscriber {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
for t in &self.targets {
if metadata.target().starts_with(t.0.as_str()) && metadata.level() <= &t.1 {
log::debug!("Enabled target: {}, level: {}", metadata.target(), metadata.level());
return true;
} else {
log::debug!("Disabled target: {}, level: {}", metadata.target(), metadata.level());
}
}
false
if metadata.target() == WASM_TARGET_KEY { return true }
self.check_target(metadata.target(), metadata.level())
mattrutherford marked this conversation as resolved.
Show resolved Hide resolved
}

fn new_span(&self, attrs: &Attributes<'_>) -> Id {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let mut values = Visitor(Vec::new());
let mut values = Visitor(FxHashMap::default());
attrs.record(&mut values);
// If this is a wasm trace, check if target/level is enabled
if let Some(wasm_target) = values.0.get(WASM_TARGET_KEY) {
if !self.check_target(wasm_target, attrs.metadata().level()) {
return Id::from_u64(id);
}
}
let span_datum = SpanDatum {
id,
name: attrs.metadata().name(),
target: attrs.metadata().target(),
name: attrs.metadata().name().to_owned(),
target: attrs.metadata().target().to_owned(),
level: attrs.metadata().level().clone(),
line: attrs.metadata().line().unwrap_or(0),
start_time: Instant::now(),
Expand All @@ -202,7 +218,12 @@ impl Subscriber for ProfilingSubscriber {
Id::from_u64(id)
}

fn record(&self, _span: &Id, _values: &Record<'_>) {}
fn record(&self, span: &Id, values: &Record<'_>) {
let mut span_data = self.span_data.lock();
if let Some(s) = span_data.get_mut(&span.into_u64()) {
values.record(&mut s.values);
}
}

fn record_follows_from(&self, _span: &Id, _follows: &Id) {}

Expand All @@ -213,23 +234,32 @@ impl Subscriber for ProfilingSubscriber {
let start_time = Instant::now();
if let Some(mut s) = span_data.get_mut(&span.into_u64()) {
s.start_time = start_time;
} else {
log::warn!("Tried to enter span {:?} that has already been closed!", span);
}
}

fn exit(&self, span: &Id) {
let mut span_data = self.span_data.lock();
let end_time = Instant::now();
let mut span_data = self.span_data.lock();
if let Some(mut s) = span_data.get_mut(&span.into_u64()) {
s.overall_time = end_time - s.start_time + s.overall_time;
}
}

fn try_close(&self, span: Id) -> bool {
let mut span_data = self.span_data.lock();
if let Some(data) = span_data.remove(&span.into_u64()) {
self.send_span(data);
let span_datum = {
let mut span_data = self.span_data.lock();
span_data.remove(&span.into_u64())
};
if let Some(mut span_datum) = span_datum {
if span_datum.name == WASM_TRACE_IDENTIFIER {
if let Some(n) = span_datum.values.0.remove(WASM_NAME_KEY) {
span_datum.name = n;
}
if let Some(t) = span_datum.values.0.remove(WASM_TARGET_KEY) {
span_datum.target = t;
}
}
self.send_span(span_datum);
};
true
}
Expand Down
7 changes: 7 additions & 0 deletions frame/support/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,7 @@ macro_rules! decl_module {
{
fn on_initialize(_block_number_not_used: $trait_instance::BlockNumber) -> $return {
$crate::sp_tracing::enter_span!("on_initialize");
$crate::wasm_tracing_span!(module_path!(), "on_initialize_wasm");
{ $( $impl )* }
}
}
Expand All @@ -1039,6 +1040,7 @@ macro_rules! decl_module {
{
fn on_initialize($param: $param_ty) -> $return {
$crate::sp_tracing::enter_span!("on_initialize");
$crate::wasm_tracing_span!(module_path!(), "on_initialize_wasm");
{ $( $impl )* }
}
}
Expand All @@ -1065,6 +1067,7 @@ macro_rules! decl_module {
{
fn on_runtime_upgrade() -> $return {
$crate::sp_tracing::enter_span!("on_runtime_upgrade");
$crate::wasm_tracing_span!(module_path!(), "on_runtime_upgrade_wasm");
{ $( $impl )* }
}
}
Expand Down Expand Up @@ -1092,6 +1095,7 @@ macro_rules! decl_module {
{
fn on_finalize(_block_number_not_used: $trait_instance::BlockNumber) {
$crate::sp_tracing::enter_span!("on_finalize");
$crate::wasm_tracing_span!(module_path!(), "on_finalize_wasm");
{ $( $impl )* }
}
}
Expand All @@ -1108,6 +1112,7 @@ macro_rules! decl_module {
{
fn on_finalize($param: $param_ty) {
$crate::sp_tracing::enter_span!("on_finalize");
$crate::wasm_tracing_span!(module_path!(), "on_finalize_wasm");
mattrutherford marked this conversation as resolved.
Show resolved Hide resolved
{ $( $impl )* }
}
}
Expand Down Expand Up @@ -1177,6 +1182,7 @@ macro_rules! decl_module {
$origin: $origin_ty $(, $param: $param_ty )*
) -> $crate::dispatch::DispatchResult {
$crate::sp_tracing::enter_span!(stringify!($name));
$crate::wasm_tracing_span!(module_path!(), concat!(stringify!($name),"_wasm"));
{ $( $impl )* }
Ok(())
}
Expand All @@ -1196,6 +1202,7 @@ macro_rules! decl_module {
$(#[doc = $doc_attr])*
$vis fn $name($origin: $origin_ty $(, $param: $param_ty )* ) -> $result {
$crate::sp_tracing::enter_span!(stringify!($name));
$crate::wasm_tracing_span!(module_path!(), concat!(stringify!($name),"_wasm"));
$( $impl )*
}
};
Expand Down
4 changes: 4 additions & 0 deletions frame/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ extern crate bitmask;

#[doc(hidden)]
pub use sp_tracing;
#[doc(hidden)]
pub use sp_io;

#[cfg(feature = "std")]
pub use serde;
Expand Down Expand Up @@ -65,6 +67,8 @@ pub mod inherent;
pub mod unsigned;
#[macro_use]
pub mod error;
#[macro_use]
pub mod wasm_tracing;
pub mod traits;
pub mod weights;

Expand Down
48 changes: 48 additions & 0 deletions frame/support/src/wasm_tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.

// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.

//! # To allow tracing in WASM execution environment
//!
//! Facilitated by `sp_io::wasm_tracing`


/// This holds a tracing span id and is to signal on drop that a tracing span has exited.
/// It must be bound to a named variable eg. `_span_guard`.
pub struct TracingSpanGuard(pub u64);
mattrutherford marked this conversation as resolved.
Show resolved Hide resolved

impl Drop for TracingSpanGuard {
fn drop(&mut self) {
crate::sp_io::wasm_tracing::exit_span(self.0);
}
}

/// Enters a tracing span, via [`sp_tracing::proxy`] measuring execution time
/// until exit from the current scope.
///
/// # Example
///
/// ```
/// frame_support::wasm_tracing_span!("target", "fn_name");
/// ```
#[macro_export]
macro_rules! wasm_tracing_span {
( $target:expr, $name:expr ) => {
#[cfg(not(feature = "std"))]
let __span_id__ = $crate::wasm_tracing::TracingSpanGuard(
mattrutherford marked this conversation as resolved.
Show resolved Hide resolved
$crate::sp_io::wasm_tracing::enter_span($target, $name)
);
}
}
Loading