Skip to content

Commit

Permalink
feat: support perf for debug
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Apr 25, 2024
1 parent d685f9f commit 2f13d31
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 14 deletions.
35 changes: 35 additions & 0 deletions Cargo.lock

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

9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ cfg-if = "1.0.0"
chrono = "0.4.37"
clap = { version = "4.5.4", features = ["derive"] }
crc32fast = "1.4.0"
dhat = { version = "0.3.3", optional = true }
dirs = "5.0.1"
env_logger = "0.11.3"
futures-util = "0.3.30"
Expand Down Expand Up @@ -67,8 +68,7 @@ urlencoding = "2.1.3"
uuid = { version = "1.8.0", features = ["v4", "fast-rng"] }

[features]
pyro = ["pyroscope", "pyroscope_pprofrs"]
# default = ["pyro"]
perf = ["pyroscope", "pyroscope_pprofrs", "dhat"]


[dev-dependencies]
Expand All @@ -81,6 +81,11 @@ codegen-units = 1
lto = true
strip = "debuginfo"

[profile.release-perf]
inherits = "release"
debug = 1
strip = "none"


[[bench]]
name = "bench"
Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ release:
cargo build --release
ls -lh target/release

perf:
cargo build --profile=release-perf --features=perf
ls -lh target/release

publish:
make build-web
cargo publish --registry crates-io --no-verify
Expand Down
1 change: 1 addition & 0 deletions src/config/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ pub fn save_config(path: &str, conf: &mut PingapConf, category: &str) -> Result<
data.servers = None;
data.locations = None;
data.upstreams = None;
data.proxy_plugins = None;
toml::to_string_pretty(&data).context(SerSnafu)?
}
};
Expand Down
26 changes: 18 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,18 @@ use std::sync::Arc;
mod acme;
mod config;
mod http_extra;
#[cfg(feature = "perf")]
mod perf;
mod plugin;
mod proxy;
#[cfg(feature = "pyro")]
mod pyroscope_client;
mod state;
mod util;
mod webhook;

#[cfg(feature = "perf")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

/// A reverse proxy like nginx.
#[derive(Parser, Debug, Default)]
#[command(author, version, about, long_about = None)]
Expand Down Expand Up @@ -150,6 +154,10 @@ fn run() -> Result<(), Box<dyn Error>> {
info!("validate config success");
return Ok(());
}

#[cfg(feature = "perf")]
info!("enable feature perf");

config::set_config_path(&args.conf);
config::set_config_hash(&conf.hash().unwrap_or_default());

Expand Down Expand Up @@ -193,12 +201,9 @@ fn run() -> Result<(), Box<dyn Error>> {
my_server.sentry = conf.sentry.clone();
my_server.bootstrap();

cfg_if::cfg_if! {
if #[cfg(feature = "pyro")] {
if let Some(url) = &conf.pyroscope{
let _ = pyroscope_client::start_pyroscope(url)?;
}
}
#[cfg(feature = "perf")]
if let Some(url) = &conf.pyroscope {
let _ = perf::start_pyroscope(url)?;
}

// TODO load from config
Expand Down Expand Up @@ -284,11 +289,16 @@ fn run() -> Result<(), Box<dyn Error>> {
info!("server is running");
let _ = get_start_time();

// TODO not process exit until pingora supports
my_server.run_forever();
Ok(())
}

fn main() {
// can not get the heap profile
// because pingora exit the process
#[cfg(feature = "perf")]
let _profiler = dhat::Profiler::new_heap();
if let Err(e) = run() {
// avoid env logger is not init
println!("{e}");
Expand Down
4 changes: 3 additions & 1 deletion src/pyroscope_client/mod.rs → src/perf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use log::info;
use pyroscope::{pyroscope::PyroscopeAgentRunning, PyroscopeAgent, PyroscopeError};
use pyroscope_pprofrs::{pprof_backend, PprofConfig};
use snafu::{ResultExt, Snafu};
Expand Down Expand Up @@ -57,7 +58,7 @@ pub fn start_pyroscope(value: &str) -> Result<PyroscopeAgent<PyroscopeAgentRunni
connect_url = connect_url.replace(query, "");
}

let mut agent = PyroscopeAgent::builder(connect_url, application_name);
let mut agent = PyroscopeAgent::builder(&connect_url, &application_name);
if !user.is_empty() {
agent = agent.basic_auth(user, password);
}
Expand All @@ -66,5 +67,6 @@ pub fn start_pyroscope(value: &str) -> Result<PyroscopeAgent<PyroscopeAgentRunni
// .tags([("app", "Rust"), ("TagB", "ValueB")].to_vec())
.build()
.context(PyroscopeSnafu)?;
info!("connect to pyroscope, app:{application_name}, url:{connect_url}");
client.start().context(PyroscopeSnafu)
}
2 changes: 2 additions & 0 deletions src/plugin/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ struct BasicConfParams {
pub webhook_type: Option<String>,
pub log_level: Option<String>,
pub sentry: Option<String>,
pub pyroscope: Option<String>,
}

#[derive(Serialize, Deserialize)]
Expand Down Expand Up @@ -264,6 +265,7 @@ impl AdminServe {
conf.webhook_type = basic_conf.webhook_type;
conf.log_level = basic_conf.log_level;
conf.sentry = basic_conf.sentry;
conf.pyroscope = basic_conf.pyroscope;
}
};
save_config(&config::get_config_path(), &mut conf, category).map_err(|e| {
Expand Down
6 changes: 6 additions & 0 deletions src/proxy/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,12 @@ impl Server {
message: err.to_string(),
})?;
tls_settings.enable_h2();
if let Some(min_version) = tls_settings.min_proto_version() {
info!("tls min proto version:{min_version:?}");
}
if let Some(max_version) = tls_settings.max_proto_version() {
info!("tls max proto version:{max_version:?}");
}
self.is_tls = true;
Some(tls_settings)
} else {
Expand Down
6 changes: 3 additions & 3 deletions src/state/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn validate_restart() -> Result<bool, Box<dyn std::error::Error>> {
#[async_trait]
impl BackgroundService for AutoRestart {
async fn start(&self, mut shutdown: ShutdownWatch) {
let mut period = interval(Duration::from_secs(60));
let mut period = interval(Duration::from_secs(90));
loop {
tokio::select! {
_ = shutdown.changed() => {
Expand All @@ -88,7 +88,7 @@ impl BackgroundService for AutoRestart {
_ = period.tick() => {
match validate_restart() {
Ok(should_restart) => {
info!("auto restart background service, should_restart:{should_restart}");
info!("auto restart background service, should restart:{should_restart}");
if should_restart {
restart();
}
Expand Down Expand Up @@ -139,7 +139,7 @@ pub fn restart_now() -> io::Result<process::Output> {
pub fn restart() {
let count = PROCESS_RESTAR_COUNT.fetch_add(1, Ordering::Relaxed) + 1;
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(90)).await;
tokio::time::sleep(Duration::from_secs(60)).await;
if count == PROCESS_RESTAR_COUNT.load(Ordering::Relaxed) {
if let Err(e) = restart_now() {
error!("Restart fail: {e}");
Expand Down
7 changes: 7 additions & 0 deletions web/src/pages/basic-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ export default function BasicInfo() {
span: 12,
category: FormItemCategory.TEXT,
},
{
id: "pyroscope",
label: "Pyroscope",
defaultValue: config.pyroscope,
span: 12,
category: FormItemCategory.TEXT,
},
{
id: "error_template",
label: "Error Template",
Expand Down
1 change: 1 addition & 0 deletions web/src/states/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ interface Config {
upstream_keepalive_pool_size?: number;
log_level?: string;
sentry?: string;
pyroscope?: string;
webhook?: string;
webhook_type?: string;
}
Expand Down

0 comments on commit 2f13d31

Please sign in to comment.