1use crate::cli::Args;
4use alloy_provider::{Provider, ProviderBuilder};
5use alloy_rpc_types_eth::SyncStatus;
6use eyre::{eyre, OptionExt, Result, WrapErr};
7#[cfg(unix)]
8use nix::sys::signal::{killpg, Signal};
9#[cfg(unix)]
10use nix::unistd::Pid;
11use reth_chainspec::Chain;
12use std::{fs, path::PathBuf, time::Duration};
13use tokio::{
14 fs::File as AsyncFile,
15 io::{AsyncBufReadExt, AsyncWriteExt, BufReader as AsyncBufReader},
16 process::Command,
17 time::{sleep, timeout},
18};
19use tracing::{debug, info, warn};
20
21pub(crate) struct NodeManager {
23 datadir: Option<String>,
24 metrics_port: u16,
25 chain: Chain,
26 use_sudo: bool,
27 binary_path: Option<std::path::PathBuf>,
28 enable_profiling: bool,
29 output_dir: PathBuf,
30 additional_reth_args: Vec<String>,
31 comparison_dir: Option<PathBuf>,
32 tracing_endpoint: Option<String>,
33 otlp_max_queue_size: usize,
34}
35
36impl NodeManager {
37 pub(crate) fn new(args: &Args) -> Self {
39 Self {
40 datadir: Some(args.datadir_path().to_string_lossy().to_string()),
41 metrics_port: args.metrics_port,
42 chain: args.chain,
43 use_sudo: args.sudo,
44 binary_path: None,
45 enable_profiling: args.profile,
46 output_dir: args.output_dir_path(),
47 additional_reth_args: args
49 .reth_args
50 .iter()
51 .filter(|s| !s.is_empty())
52 .cloned()
53 .collect(),
54 comparison_dir: None,
55 tracing_endpoint: args.traces.otlp.as_ref().map(|u| u.to_string()),
56 otlp_max_queue_size: args.otlp_max_queue_size,
57 }
58 }
59
60 pub(crate) fn set_comparison_dir(&mut self, dir: PathBuf) {
62 self.comparison_dir = Some(dir);
63 }
64
65 fn get_log_file_path(&self, ref_type: &str) -> Result<PathBuf> {
67 let comparison_dir = self
68 .comparison_dir
69 .as_ref()
70 .ok_or_eyre("Comparison directory not set. Call set_comparison_dir first.")?;
71
72 let log_dir = comparison_dir.join(ref_type);
74
75 fs::create_dir_all(&log_dir)
77 .wrap_err(format!("Failed to create log directory: {:?}", log_dir))?;
78
79 let log_file = log_dir.join("reth_node.log");
80 Ok(log_file)
81 }
82
83 fn get_perf_sample_rate(&self) -> Option<String> {
85 let perf_rate_file = "/proc/sys/kernel/perf_event_max_sample_rate";
86 if let Ok(content) = fs::read_to_string(perf_rate_file) {
87 let rate_str = content.trim();
88 if !rate_str.is_empty() {
89 if let Ok(system_rate) = rate_str.parse::<u32>() {
90 let capped_rate = std::cmp::min(system_rate, 10000);
91 info!(
92 "Detected perf_event_max_sample_rate: {}, using: {}",
93 system_rate, capped_rate
94 );
95 return Some(capped_rate.to_string());
96 }
97 warn!("Failed to parse perf_event_max_sample_rate: {}", rate_str);
98 }
99 }
100 None
101 }
102
103 async fn get_samply_path(&self) -> Result<String> {
105 let output = Command::new("which")
106 .arg("samply")
107 .output()
108 .await
109 .wrap_err("Failed to execute 'which samply' command")?;
110
111 if !output.status.success() {
112 return Err(eyre!("samply not found in PATH"));
113 }
114
115 let samply_path = String::from_utf8(output.stdout)
116 .wrap_err("samply path is not valid UTF-8")?
117 .trim()
118 .to_string();
119
120 if samply_path.is_empty() {
121 return Err(eyre!("which samply returned empty path"));
122 }
123
124 Ok(samply_path)
125 }
126
127 fn build_reth_args(
129 &self,
130 binary_path_str: &str,
131 additional_args: &[String],
132 ref_type: &str,
133 ) -> (Vec<String>, String) {
134 let mut reth_args = vec![binary_path_str.to_string(), "node".to_string()];
135
136 let chain_str = self.chain.to_string();
138 if chain_str != "mainnet" {
139 reth_args.extend_from_slice(&["--chain".to_string(), chain_str.clone()]);
140 }
141
142 if let Some(ref datadir) = self.datadir {
144 reth_args.extend_from_slice(&["--datadir".to_string(), datadir.clone()]);
145 }
146
147 let metrics_arg = format!("0.0.0.0:{}", self.metrics_port);
149 reth_args.extend_from_slice(&[
150 "--engine.accept-execution-requests-hash".to_string(),
151 "--metrics".to_string(),
152 metrics_arg,
153 "--http".to_string(),
154 "--http.api".to_string(),
155 "eth".to_string(),
156 "--disable-discovery".to_string(),
157 "--trusted-only".to_string(),
158 ]);
159
160 if let Some(ref endpoint) = self.tracing_endpoint {
162 info!("Enabling OTLP tracing export to: {} (service: reth-{})", endpoint, ref_type);
163 reth_args.push(format!("--tracing-otlp={}", endpoint));
165 }
166
167 reth_args.extend_from_slice(&self.additional_reth_args);
170
171 reth_args.extend_from_slice(additional_args);
173
174 (reth_args, chain_str)
175 }
176
177 async fn create_profiling_command(
179 &self,
180 ref_type: &str,
181 reth_args: &[String],
182 ) -> Result<Command> {
183 let profile_dir = self.output_dir.join("profiles");
185 fs::create_dir_all(&profile_dir).wrap_err("Failed to create profiles directory")?;
186
187 let profile_path = profile_dir.join(format!("{}.json.gz", ref_type));
188 info!("Starting reth node with samply profiling...");
189 info!("Profile output: {:?}", profile_path);
190
191 let samply_path = self.get_samply_path().await?;
193
194 let mut cmd = if self.use_sudo {
195 let mut sudo_cmd = Command::new("sudo");
196 sudo_cmd.arg(&samply_path);
197 sudo_cmd
198 } else {
199 Command::new(&samply_path)
200 };
201
202 cmd.args(["record", "--save-only", "-o", &profile_path.to_string_lossy()]);
204
205 if let Some(rate) = self.get_perf_sample_rate() {
207 cmd.args(["--rate", &rate]);
208 }
209
210 cmd.arg("--");
212 cmd.args(reth_args);
213
214 cmd.env("RUST_LOG_STYLE", "never");
216
217 Ok(cmd)
218 }
219
220 fn create_direct_command(&self, reth_args: &[String]) -> Command {
222 let binary_path = &reth_args[0];
223
224 let mut cmd = if self.use_sudo {
225 info!("Starting reth node with sudo...");
226 let mut sudo_cmd = Command::new("sudo");
227 sudo_cmd.args(reth_args);
228 sudo_cmd
229 } else {
230 info!("Starting reth node...");
231 let mut reth_cmd = Command::new(binary_path);
232 reth_cmd.args(&reth_args[1..]); reth_cmd
234 };
235
236 cmd.env("RUST_LOG_STYLE", "never");
238
239 cmd
240 }
241
242 pub(crate) async fn start_node(
245 &mut self,
246 binary_path: &std::path::Path,
247 _git_ref: &str,
248 ref_type: &str,
249 additional_args: &[String],
250 ) -> Result<(tokio::process::Child, String)> {
251 self.binary_path = Some(binary_path.to_path_buf());
253
254 let binary_path_str = binary_path.to_string_lossy();
255 let (reth_args, _) = self.build_reth_args(&binary_path_str, additional_args, ref_type);
256
257 let reth_command = shlex::try_join(reth_args.iter().map(|s| s.as_str()))
259 .wrap_err("Failed to format reth command string")?;
260
261 if !self.additional_reth_args.is_empty() {
263 info!("Using common additional reth arguments: {:?}", self.additional_reth_args);
264 }
265 if !additional_args.is_empty() {
266 info!("Using reference-specific additional reth arguments: {:?}", additional_args);
267 }
268
269 let mut cmd = if self.enable_profiling {
270 self.create_profiling_command(ref_type, &reth_args).await?
271 } else {
272 self.create_direct_command(&reth_args)
273 };
274
275 #[cfg(unix)]
277 {
278 cmd.process_group(0);
279 }
280
281 if self.tracing_endpoint.is_some() {
283 cmd.env("OTEL_BSP_MAX_QUEUE_SIZE", self.otlp_max_queue_size.to_string()); cmd.env("OTEL_BLRP_MAX_QUEUE_SIZE", "10000"); cmd.env("OTEL_SERVICE_NAME", format!("reth-{}", ref_type));
288 }
289
290 debug!("Executing reth command: {cmd:?}");
291
292 let mut child = cmd
293 .stdout(std::process::Stdio::piped())
294 .stderr(std::process::Stdio::piped())
295 .kill_on_drop(true) .spawn()
297 .wrap_err("Failed to start reth node")?;
298
299 info!(
300 "Reth node started with PID: {:?} (binary: {})",
301 child.id().ok_or_eyre("Reth node is not running")?,
302 binary_path_str
303 );
304
305 let log_file_path = self.get_log_file_path(ref_type)?;
307 info!("Reth node logs will be saved to: {:?}", log_file_path);
308
309 if let Some(stdout) = child.stdout.take() {
311 let log_file = AsyncFile::create(&log_file_path)
312 .await
313 .wrap_err(format!("Failed to create log file: {:?}", log_file_path))?;
314 tokio::spawn(async move {
315 let reader = AsyncBufReader::new(stdout);
316 let mut lines = reader.lines();
317 let mut log_file = log_file;
318 while let Ok(Some(line)) = lines.next_line().await {
319 debug!("[RETH] {}", line);
320 let log_line = format!("{}\n", line);
322 if let Err(e) = log_file.write_all(log_line.as_bytes()).await {
323 debug!("Failed to write to log file: {}", e);
324 }
325 }
326 });
327 }
328
329 if let Some(stderr) = child.stderr.take() {
330 let log_file = AsyncFile::options()
331 .create(true)
332 .append(true)
333 .open(&log_file_path)
334 .await
335 .wrap_err(format!("Failed to open log file for stderr: {:?}", log_file_path))?;
336 tokio::spawn(async move {
337 let reader = AsyncBufReader::new(stderr);
338 let mut lines = reader.lines();
339 let mut log_file = log_file;
340 while let Ok(Some(line)) = lines.next_line().await {
341 debug!("[RETH] {}", line);
342 let log_line = format!("{}\n", line);
344 if let Err(e) = log_file.write_all(log_line.as_bytes()).await {
345 debug!("Failed to write to log file: {}", e);
346 }
347 }
348 });
349 }
350
351 sleep(Duration::from_secs(5)).await;
353
354 Ok((child, reth_command))
355 }
356
357 pub(crate) async fn wait_for_node_ready_and_get_tip(&self) -> Result<u64> {
359 info!("Waiting for node to be ready and synced...");
360
361 let max_wait = Duration::from_secs(120); let check_interval = Duration::from_secs(2);
363 let rpc_url = "http://localhost:8545";
364
365 let url = rpc_url.parse().map_err(|e| eyre!("Invalid RPC URL '{}': {}", rpc_url, e))?;
367 let provider = ProviderBuilder::new().connect_http(url);
368
369 timeout(max_wait, async {
370 loop {
371 match provider.syncing().await {
373 Ok(sync_result) => {
374 match sync_result {
375 SyncStatus::Info(sync_info) => {
376 debug!("Node is still syncing {sync_info:?}, waiting...");
377 }
378 _ => {
379 match provider.get_block_number().await {
381 Ok(tip) => {
382 info!("Node is ready and not syncing at block: {}", tip);
383 return Ok(tip);
384 }
385 Err(e) => {
386 debug!("Failed to get block number: {}", e);
387 }
388 }
389 }
390 }
391 }
392 Err(e) => {
393 debug!("Node RPC not ready yet or failed to check sync status: {}", e);
394 }
395 }
396
397 sleep(check_interval).await;
398 }
399 })
400 .await
401 .wrap_err("Timed out waiting for node to be ready and synced")?
402 }
403
404 pub(crate) async fn stop_node(&self, child: &mut tokio::process::Child) -> Result<()> {
406 let pid = child.id().expect("Child process ID should be available");
407
408 match child.try_wait() {
410 Ok(Some(status)) => {
411 info!("Reth node (PID: {}) has already exited with status: {:?}", pid, status);
412 return Ok(());
413 }
414 Ok(None) => {
415 info!("Stopping process gracefully with SIGINT (PID: {})...", pid);
417 }
418 Err(e) => {
419 return Err(eyre!("Failed to check process status: {}", e));
420 }
421 }
422
423 #[cfg(unix)]
424 {
425 let nix_pgid = Pid::from_raw(pid as i32);
427
428 match killpg(nix_pgid, Signal::SIGINT) {
429 Ok(()) => {}
430 Err(nix::errno::Errno::ESRCH) => {
431 info!("Process group {} has already exited", pid);
432 }
433 Err(e) => {
434 return Err(eyre!("Failed to send SIGINT to process group {}: {}", pid, e));
435 }
436 }
437 }
438
439 #[cfg(not(unix))]
440 {
441 let output = Command::new("taskkill")
443 .args(["/PID", &pid.to_string(), "/F"])
444 .output()
445 .await
446 .wrap_err("Failed to execute taskkill command")?;
447
448 if !output.status.success() {
449 let stderr = String::from_utf8_lossy(&output.stderr);
450 if stderr.contains("not found") || stderr.contains("not exist") {
452 info!("Process {} has already exited", pid);
453 } else {
454 return Err(eyre!("Failed to kill process {}: {}", pid, stderr));
455 }
456 }
457 }
458
459 match child.wait().await {
461 Ok(status) => {
462 info!("Reth node (PID: {}) exited with status: {:?}", pid, status);
463 }
464 Err(e) => {
465 debug!("Error waiting for process exit (may have already exited): {}", e);
467 }
468 }
469
470 Ok(())
471 }
472
473 pub(crate) async fn unwind_to_block(&self, block_number: u64) -> Result<()> {
475 if self.use_sudo {
476 info!("Unwinding node to block: {} (with sudo)", block_number);
477 } else {
478 info!("Unwinding node to block: {}", block_number);
479 }
480
481 let binary_path = self
483 .binary_path
484 .as_ref()
485 .map(|p| p.to_string_lossy().to_string())
486 .unwrap_or_else(|| "./target/profiling/reth".to_string());
487
488 let mut cmd = if self.use_sudo {
489 let mut sudo_cmd = Command::new("sudo");
490 sudo_cmd.args([&binary_path, "stage", "unwind"]);
491 sudo_cmd
492 } else {
493 let mut reth_cmd = Command::new(&binary_path);
494 reth_cmd.args(["stage", "unwind"]);
495 reth_cmd
496 };
497
498 let chain_str = self.chain.to_string();
500 if chain_str != "mainnet" {
501 cmd.args(["--chain", &chain_str]);
502 }
503
504 if let Some(ref datadir) = self.datadir {
506 cmd.args(["--datadir", datadir]);
507 }
508
509 cmd.args(["to-block", &block_number.to_string()]);
510
511 cmd.env("RUST_LOG_STYLE", "never");
513
514 debug!("Executing reth unwind command: {:?}", cmd);
516
517 let mut child = cmd
518 .stdout(std::process::Stdio::piped())
519 .stderr(std::process::Stdio::piped())
520 .spawn()
521 .wrap_err("Failed to start unwind command")?;
522
523 if let Some(stdout) = child.stdout.take() {
525 tokio::spawn(async move {
526 let reader = AsyncBufReader::new(stdout);
527 let mut lines = reader.lines();
528 while let Ok(Some(line)) = lines.next_line().await {
529 debug!("[RETH-UNWIND] {}", line);
530 }
531 });
532 }
533
534 if let Some(stderr) = child.stderr.take() {
535 tokio::spawn(async move {
536 let reader = AsyncBufReader::new(stderr);
537 let mut lines = reader.lines();
538 while let Ok(Some(line)) = lines.next_line().await {
539 debug!("[RETH-UNWIND] {}", line);
540 }
541 });
542 }
543
544 let status = child.wait().await.wrap_err("Failed to wait for unwind command")?;
546
547 if !status.success() {
548 return Err(eyre!("Unwind command failed with exit code: {:?}", status.code()));
549 }
550
551 info!("Unwound to block: {}", block_number);
552 Ok(())
553 }
554}