1#[cfg(all(target_os = "linux", target_env = "gnu"))]
19use std::ffi::CStr;
20use std::sync::atomic::{AtomicBool, Ordering};
21
22use nautilus_core::{UUID4, consts::NAUTILUS_VERSION_CORE};
23use nautilus_model::{
24 identifiers::TraderId,
25 types::fixed::{FIXED_PRECISION, HIGH_PRECISION_MODE, PRECISION_BYTES},
26};
27use sysinfo::System;
28use ustr::Ustr;
29
30use crate::{enums::LogColor, logging::log_info};
31
32const GIT_COMMIT_LEN: usize = 12;
33static MIMALLOC_REGISTERED: AtomicBool = AtomicBool::new(false);
34
35#[cfg(panic = "abort")]
36const PANIC_STRATEGY: &str = "abort";
37#[cfg(panic = "unwind")]
38const PANIC_STRATEGY: &str = "unwind";
39
40const BUILD_VERSIONS: &[(&str, &str)] = &[
41 ("git_commit", env!("NAUTILUS_BUILD_GIT_COMMIT")),
42 ("rustc", env!("NAUTILUS_BUILD_RUSTC_VERSION")),
43 ("target", env!("NAUTILUS_BUILD_TARGET")),
44 ("profile", env!("NAUTILUS_BUILD_PROFILE")),
45 ("panic", PANIC_STRATEGY),
46 ("cargo_lock", env!("NAUTILUS_BUILD_CARGO_LOCK_CRC32")),
47 #[cfg(all(target_os = "linux", target_env = "gnu"))]
48 ("libc_crate", env!("NAUTILUS_BUILD_LIBC_VERSION")),
49 ("rust_decimal", env!("NAUTILUS_BUILD_RUST_DECIMAL_VERSION")),
50];
51
52#[cfg(feature = "live")]
53const LIVE_VERSIONS: &[(&str, &str)] = &[
54 ("rustls", env!("NAUTILUS_BUILD_RUSTLS_VERSION")),
55 ("aws_lc_rs", env!("NAUTILUS_BUILD_AWS_LC_RS_VERSION")),
56 ("tokio", env!("NAUTILUS_BUILD_TOKIO_VERSION")),
57];
58
59#[cfg(feature = "python")]
60const PYTHON_VERSIONS: &[(&str, &str)] = &[
61 ("pyo3", env!("NAUTILUS_BUILD_PYO3_VERSION")),
62 (
63 "pyo3_async_runtimes",
64 env!("NAUTILUS_BUILD_PYO3_ASYNC_RUNTIMES_VERSION"),
65 ),
66];
67
68pub fn register_allocator_mimalloc() {
73 MIMALLOC_REGISTERED.store(true, Ordering::Release);
74}
75
76#[rustfmt::skip]
78pub fn log_header(trader_id: TraderId, machine_id: &str, instance_id: UUID4, component: Ustr) {
79 let mut sys = match System::new() {
80 Ok(sys) => sys,
81 Err(e) => {
82 log::warn!("Failed to query system information: {e}");
83 return;
84 }
85 };
86 sys.refresh_cpu_all();
87 sys.refresh_memory();
88
89 let c = component;
90
91 let kernel_version = System::kernel_version().map_or(String::new(), |v| format!("kernel-{v} "));
92 let os_version = System::long_os_version().unwrap_or_default();
93 let pid = std::process::id();
94
95 header_sepr(c, "=================================================================");
96 header_sepr(c, " NAUTILUS TRADER - Automated Algorithmic Trading Platform");
97 header_sepr(c, " by Nautech Systems Pty Ltd.");
98 header_sepr(c, " Copyright (C) 2015-2026. All rights reserved.");
99 header_sepr(c, "=================================================================");
100 header_line(c, "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⡤⠤⠤⠤⠤⠤⠤⠤⢤⡀⠀⠀⠀⠀⠀⠀");
101 header_line(c, "⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⠤⠖⠚⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⠁⠀⠀⠀⠀⠀⠀");
102 header_line(c, "⠀⠀⠀⠀⠀⠀⢀⣠⠖⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡴⠚⠁⠀⠀⠀⠀⠀⠀⠀");
103 header_line(c, "⠀⠀⠀⠀⢀⡴⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀");
104 header_line(c, "⠀⠀⠀⣠⠏⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⠤⠖⠒⠒⠒⠒⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀");
105 header_line(c, "⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⢀⡖⠋⣠⢴⢪⠞⣩⢟⡭⠵⢤⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀");
106 header_line(c, "⠀⠀⣦⡙⠦⣄⡀⠀⢀⣠⠴⠋⢠⡐⣇⢸⡘⢦⡇⣏⡴⣋⡭⠖⠮⢥⡀⠀⠀⠀⠀⠀⠀⠀");
107 header_line(c, "⠀⠀⢸⡉⠓⠦⠭⠭⠭⠴⣺⠃⠸⣷⢬⣓⣛⠒⠩⣌⢡⡷⢒⣫⠭⣝⡛⠆⠀⠀⠀⠀⠀⠀");
108 header_line(c, "⠀⠀⠀⠙⠦⢤⣀⣠⠤⠞⣡⠞⡆⠺⣭⣭⡷⢇⣷⡻⠡⠾⣛⣒⠦⢤⡙⡆⠀⠀⠀⠀⠀⠀");
109 header_line(c, "⠀⠀⠀⠈⠳⣖⠒⠒⠒⠋⠁⣠⠇⡼⢦⠀⣌⡉⢥⣄⣛⡻⢥⡈⠉⢳⡙⠇⠀⠀⠀⠀⠀⠀");
110 header_line(c, "⠀⠀⠀⠀⠀⠈⠙⣒⣒⣒⣋⡥⠞⠁⣸⠃⡇⠙⢦⢹⠀⠙⡆⢳⢀⡴⠃⠀⠀⠀⠀⠀⠀⠀");
111 header_line(c, "⠀⠀⠀⠀⠀⠀⠀⠈⠙⠒⠦⠤⠴⣚⣡⠞⠁⣠⠏⡼⢀⣠⠇⠞⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀");
112 header_line(c, "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠑⠚⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀");
113 header_sepr(c, "=================================================================");
114 header_sepr(c, " SYSTEM SPECIFICATION");
115 header_sepr(c, "=================================================================");
116
117 if let Some(cpu) = sys.cpus().first() {
118 header_line(c, &format!("CPU architecture: {}", cpu.brand()));
119 header_line(c, &format!("CPU(s): {} @ {} MHz", sys.cpus().len(), cpu.frequency()));
120 } else {
121 header_line(c, "CPU: unknown");
122 }
123 header_line(c, &format!("OS: {kernel_version}{os_version}"));
124
125 log_sysinfo(component);
126
127 header_sepr(c, "=================================================================");
128 header_sepr(c, " IDENTIFIERS");
129 header_sepr(c, "=================================================================");
130 header_line(c, &format!("trader_id: {trader_id}"));
131 header_line(c, &format!("machine_id: {machine_id}"));
132 header_line(c, &format!("instance_id: {instance_id}"));
133 header_line(c, &format!("PID: {pid}"));
134
135 header_sepr(c, "=================================================================");
136 header_sepr(c, " VERSIONING");
137 header_sepr(c, "=================================================================");
138
139 #[cfg(not(feature = "python"))]
140 log_rust_versioning(c);
141
142 #[cfg(feature = "python")]
143 if python_available() {
144 log_python_versioning(c);
145 } else {
146 log_rust_versioning(c);
147 }
148
149 header_sepr(c, "=================================================================");
150}
151
152#[rustfmt::skip]
153fn log_rust_versioning(c: Ustr) {
154 header_line(c, &format!("nautilus_trader: {NAUTILUS_VERSION_CORE}"));
155 log_build_versioning(c);
156 log_optional_versioning(c);
157}
158
159#[cfg(feature = "python")]
160#[rustfmt::skip]
161fn log_python_versioning(c: Ustr) {
162 let package = "nautilus_trader";
163 header_line(c, &format!("{package}: {}", python_package_version(package)));
164 header_line(c, &format!("nautilus_core: {NAUTILUS_VERSION_CORE}"));
165 header_line(c, &format!("python: {}", python_version()));
166 log_build_versioning(c);
167 log_optional_versioning(c);
168
169 for package in ["numpy", "pandas", "msgspec", "pyarrow", "pytz", "uvloop"] {
171 if let Some(version) = python_package_version_opt(package) {
172 header_line(c, &format!("{package}: {version}"));
173 }
174 }
175}
176
177#[rustfmt::skip]
178fn log_build_versioning(c: Ustr) {
179 for (name, version) in build_versions() {
180 header_line(c, &format!("{name}: {version}"));
181 }
182}
183
184#[rustfmt::skip]
185fn log_optional_versioning(c: Ustr) {
186 #[cfg(feature = "build-info-event-store")]
187 header_line(c, &format!("event_store: {}", event_store_version()));
188
189 #[cfg(feature = "live")]
190 for (name, version) in live_versions() {
191 header_line(c, &format!("{name}: {version}"));
192 }
193
194 #[cfg(feature = "python")]
195 for (name, version) in python_versions() {
196 header_line(c, &format!("{name}: {version}"));
197 }
198
199 #[cfg(not(any(
200 feature = "live",
201 feature = "python",
202 feature = "build-info-event-store"
203 )))]
204 let _ = c;
205}
206
207#[cfg(feature = "live")]
208fn live_versions() -> impl Iterator<Item = (&'static str, &'static str)> {
209 LIVE_VERSIONS
210 .iter()
211 .copied()
212 .filter(|(_, version)| !version.is_empty())
213}
214
215#[cfg(feature = "python")]
216fn python_versions() -> impl Iterator<Item = (&'static str, &'static str)> {
217 PYTHON_VERSIONS
218 .iter()
219 .copied()
220 .filter(|(_, version)| !version.is_empty())
221}
222
223#[cfg(feature = "build-info-event-store")]
224fn event_store_version() -> String {
225 let version = env!("NAUTILUS_BUILD_REDB_VERSION");
226 if version.is_empty() {
227 "redb".to_string()
228 } else {
229 format!("redb {version}")
230 }
231}
232
233fn build_versions() -> Vec<(&'static str, String)> {
234 let mut versions = BUILD_VERSIONS
235 .iter()
236 .filter(|(_, version)| !version.is_empty())
237 .map(|(name, version)| (*name, display_version(name, version)))
238 .collect::<Vec<_>>();
239
240 let precision_index = versions
241 .iter()
242 .position(|(name, _)| *name == "panic")
243 .map_or(versions.len(), |index| index + 1);
244 versions.insert(precision_index, ("precision", precision_version()));
245
246 let allocator_index = versions
247 .iter()
248 .position(|(name, _)| *name == "precision")
249 .map_or(versions.len(), |index| index + 1);
250 versions.insert(allocator_index, ("allocator", allocator_version()));
251
252 #[cfg(all(target_os = "linux", target_env = "gnu"))]
253 {
254 if let Some(version) = libc_runtime_version() {
255 let index = versions
256 .iter()
257 .position(|(name, _)| matches!(*name, "cargo_lock" | "libc_crate"))
258 .unwrap_or(versions.len());
259 versions.insert(index, ("libc_runtime", version));
260 }
261 }
262
263 versions
264}
265
266fn precision_version() -> String {
267 let mode = if HIGH_PRECISION_MODE == 1 {
268 "high"
269 } else {
270 "standard"
271 };
272 let bits = PRECISION_BYTES * 8;
273 format!("{mode} ({bits}-bit, {FIXED_PRECISION} dp)")
274}
275
276fn allocator_version() -> String {
277 allocator_version_for(MIMALLOC_REGISTERED.load(Ordering::Acquire))
278}
279
280fn allocator_version_for(mimalloc: bool) -> String {
281 if mimalloc {
282 let version = env!("NAUTILUS_BUILD_MIMALLOC_VERSION");
283 if version.is_empty() {
284 "mimalloc".to_string()
285 } else {
286 format!("mimalloc {version}")
287 }
288 } else {
289 "system".to_string()
290 }
291}
292
293fn display_version(name: &str, version: &str) -> String {
294 match name {
295 "cargo_lock" => version
296 .strip_prefix("crc32:")
297 .unwrap_or(version)
298 .to_string(),
299 "git_commit" => version.get(..GIT_COMMIT_LEN).unwrap_or(version).to_string(),
300 _ => version.to_string(),
301 }
302}
303
304#[cfg(all(target_os = "linux", target_env = "gnu"))]
305#[allow(unsafe_code)]
306fn libc_runtime_version() -> Option<String> {
307 let version = unsafe { libc::gnu_get_libc_version() };
309 if version.is_null() {
310 return None;
311 }
312
313 let version = unsafe { CStr::from_ptr(version) }.to_str().ok()?;
315 Some(format!("glibc {version}"))
316}
317
318#[cfg(feature = "python")]
319#[inline]
320#[allow(unsafe_code)]
321fn python_available() -> bool {
322 unsafe { pyo3::ffi::Py_IsInitialized() != 0 }
325}
326
327#[rustfmt::skip]
329pub fn log_sysinfo(component: Ustr) {
330 let mut sys = match System::new() {
331 Ok(sys) => sys,
332 Err(e) => {
333 log::warn!("Failed to query system information: {e}");
334 return;
335 }
336 };
337 sys.refresh_memory();
338
339 let c = component;
340
341 let ram_total = sys.total_memory();
342 let ram_used = sys.used_memory();
343 let ram_used_p = (ram_used as f64 / ram_total as f64) * 100.0;
344 let ram_avail = ram_total - ram_used;
345 let ram_avail_p = (ram_avail as f64 / ram_total as f64) * 100.0;
346
347 header_sepr(c, "=================================================================");
348 header_sepr(c, " MEMORY USAGE");
349 header_sepr(c, "=================================================================");
350 header_line(c, &format!("RAM-Total: {:.2} GiB", bytes_to_gib(ram_total)));
351 header_line(c, &format!("RAM-Used: {:.2} GiB ({:.2}%)", bytes_to_gib(ram_used), ram_used_p));
352 header_line(c, &format!("RAM-Avail: {:.2} GiB ({:.2}%)", bytes_to_gib(ram_avail), ram_avail_p));
353
354 let swap_total = sys.total_swap();
355 if swap_total > 0 {
356 let swap_used = sys.used_swap();
357 let swap_used_p = (swap_used as f64 / swap_total as f64) * 100.0;
358 let swap_avail = swap_total.saturating_sub(swap_used);
359 let swap_avail_p = (swap_avail as f64 / swap_total as f64) * 100.0;
360 header_line(c, &format!("Swap-Total: {:.2} GiB", bytes_to_gib(swap_total)));
361 header_line(c, &format!("Swap-Used: {:.2} GiB ({:.2}%)", bytes_to_gib(swap_used), swap_used_p));
362 header_line(c, &format!("Swap-Avail: {:.2} GiB ({:.2}%)", bytes_to_gib(swap_avail), swap_avail_p));
363 } else {
364 header_line(c, "Swap: disabled");
365 }
366}
367
368fn header_sepr(c: Ustr, s: &str) {
369 log_info!("{}", s, color = LogColor::Cyan, component = c.as_str());
370}
371
372fn header_line(c: Ustr, s: &str) {
373 log_info!("{}", s, component = c.as_str());
374}
375
376fn bytes_to_gib(b: u64) -> f64 {
377 b as f64 / (2u64.pow(30) as f64)
378}
379
380#[cfg(feature = "python")]
381fn python_package_version(package: &str) -> String {
382 nautilus_core::python::version::get_python_package_version(package)
383}
384
385#[cfg(feature = "python")]
386fn python_package_version_opt(package: &str) -> Option<String> {
387 nautilus_core::python::version::get_python_package_version_opt(package)
388}
389
390#[cfg(feature = "python")]
391fn python_version() -> String {
392 nautilus_core::python::version::get_python_version()
393}
394
395#[cfg(test)]
396mod tests {
397 use rstest::rstest;
398
399 use super::*;
400
401 #[rstest]
402 fn test_build_versions_match_compiled_metadata() {
403 let versions = build_versions();
404
405 for (name, expected) in BUILD_VERSIONS {
406 let expected = (!expected.is_empty()).then(|| display_version(name, expected));
407 assert_eq!(version(&versions, name), expected.as_deref());
408 }
409 }
410
411 #[rstest]
412 fn test_build_modes_match_compiled_configuration() {
413 let versions = build_versions();
414 let panic_index = versions
415 .iter()
416 .position(|(name, _)| *name == "panic")
417 .expect("panic version should be present");
418 let precision_index = versions
419 .iter()
420 .position(|(name, _)| *name == "precision")
421 .expect("precision version should be present");
422 let allocator_index = versions
423 .iter()
424 .position(|(name, _)| *name == "allocator")
425 .expect("allocator version should be present");
426
427 assert_eq!(version(&versions, "panic"), Some(PANIC_STRATEGY));
428 assert_eq!(precision_index, panic_index + 1);
429 assert_eq!(allocator_index, precision_index + 1);
430 assert_eq!(
431 version(&versions, "precision"),
432 Some(precision_version().as_str()),
433 );
434 assert_eq!(version(&versions, "allocator"), Some("system"),);
435 }
436
437 #[rstest]
440 fn test_precision_version_reports_the_compiled_precision_mode() {
441 let (expected_mode, expected_bits) = match PRECISION_BYTES {
442 16 => ("high", 128),
443 8 => ("standard", 64),
444 other => panic!("unexpected PRECISION_BYTES {other}"),
445 };
446
447 assert_eq!(
448 precision_version(),
449 format!("{expected_mode} ({expected_bits}-bit, {FIXED_PRECISION} dp)")
450 );
451 }
452
453 #[rstest]
454 #[case(0, 0.0)]
455 #[case(1 << 30, 1.0)]
456 #[case(3 << 29, 1.5)]
457 #[case((1 << 30) * 64, 64.0)]
458 fn test_bytes_to_gib_converts_from_binary_gigabytes(#[case] bytes: u64, #[case] expected: f64) {
459 assert_eq!(bytes_to_gib(bytes), expected);
460 }
461
462 #[rstest]
463 #[case("cargo_lock", "crc32:0a1b2c3d", "0a1b2c3d")]
464 #[case("cargo_lock", "0a1b2c3d", "0a1b2c3d")]
465 #[case("git_commit", "0123456789abcdef0123", "0123456789ab")]
466 #[case("git_commit", "0123abc", "0123abc")]
467 #[case("rustc", "1.90.0", "1.90.0")]
468 fn test_display_version_trims_only_the_named_fields(
469 #[case] name: &str,
470 #[case] version: &str,
471 #[case] expected: &str,
472 ) {
473 assert_eq!(display_version(name, version), expected);
474 }
475
476 #[rstest]
477 fn test_allocator_version_formats() {
478 let mimalloc = env!("NAUTILUS_BUILD_MIMALLOC_VERSION");
479 let expected = if mimalloc.is_empty() {
480 "mimalloc".to_string()
481 } else {
482 format!("mimalloc {mimalloc}")
483 };
484
485 assert_eq!(allocator_version_for(false), "system");
486 assert_eq!(allocator_version_for(true), expected);
487 }
488
489 #[cfg(feature = "live")]
490 #[rstest]
491 fn test_live_versions_match_compiled_metadata() {
492 let versions = live_versions().collect::<Vec<_>>();
493
494 for (_, expected) in LIVE_VERSIONS {
495 assert!(!expected.is_empty());
496 }
497 assert_eq!(versions, LIVE_VERSIONS);
498 assert_eq!(versions.last().map(|(name, _)| *name), Some("tokio"));
499 }
500
501 #[cfg(feature = "python")]
502 #[rstest]
503 fn test_python_versions_follow_tokio() {
504 let live_versions = live_versions().collect::<Vec<_>>();
505 let python_versions = python_versions().collect::<Vec<_>>();
506
507 for (_, expected) in PYTHON_VERSIONS {
508 assert!(!expected.is_empty());
509 }
510 assert_eq!(python_versions, PYTHON_VERSIONS);
511 assert_eq!(live_versions.last().map(|(name, _)| *name), Some("tokio"));
512 assert_eq!(
513 python_versions
514 .iter()
515 .map(|(name, _)| *name)
516 .collect::<Vec<_>>(),
517 ["pyo3", "pyo3_async_runtimes"],
518 );
519 }
520
521 #[cfg(feature = "build-info-event-store")]
522 #[rstest]
523 fn test_event_store_version_matches_compiled_metadata() {
524 let redb = env!("NAUTILUS_BUILD_REDB_VERSION");
525
526 assert!(!redb.is_empty());
527 assert_eq!(event_store_version(), format!("redb {redb}"));
528 }
529
530 #[rstest]
531 fn test_cargo_lock_fingerprint_format() {
532 const CRC32_HEX_LEN: usize = 8;
533
534 let versions = build_versions();
535 let Some(fingerprint) = version(&versions, "cargo_lock") else {
536 return;
537 };
538 let embedded = env!("NAUTILUS_BUILD_CARGO_LOCK_CRC32");
539 let Some(checksum) = embedded.strip_prefix("crc32:") else {
540 panic!("embedded cargo_lock fingerprint should use the crc32 prefix");
541 };
542
543 assert_eq!(checksum.len(), CRC32_HEX_LEN);
544 assert!(checksum.bytes().all(|byte| byte.is_ascii_hexdigit()));
545 assert_eq!(fingerprint.len(), CRC32_HEX_LEN);
546 assert_eq!(fingerprint, checksum);
547 }
548
549 #[rstest]
550 fn test_git_commit_format() {
551 let versions = build_versions();
552 let Some(commit) = version(&versions, "git_commit") else {
553 return;
554 };
555
556 assert_eq!(commit.len(), GIT_COMMIT_LEN);
557 assert!(commit.bytes().all(|byte| byte.is_ascii_hexdigit()));
558 }
559
560 #[cfg(all(target_os = "linux", target_env = "gnu"))]
561 #[rstest]
562 fn test_libc_runtime_version_reports_glibc() {
563 let version = libc_runtime_version().expect("glibc should report its runtime version");
564 let versions = build_versions();
565 let runtime_index = versions
566 .iter()
567 .position(|(name, _)| *name == "libc_runtime")
568 .expect("libc runtime version should be present");
569 let cargo_lock_index = versions.iter().position(|(name, _)| *name == "cargo_lock");
570 let libc_crate_index = versions.iter().position(|(name, _)| *name == "libc_crate");
571
572 assert!(version.starts_with("glibc "));
573 assert!(
574 version["glibc ".len()..]
575 .bytes()
576 .any(|byte| byte.is_ascii_digit())
577 );
578
579 if let Some(cargo_lock_index) = cargo_lock_index {
580 assert_eq!(cargo_lock_index, runtime_index + 1);
581 }
582
583 if let Some(libc_crate_index) = libc_crate_index {
584 assert_eq!(
585 libc_crate_index,
586 cargo_lock_index.unwrap_or(runtime_index) + 1,
587 );
588 }
589 }
590
591 fn version<'a>(versions: &'a [(&str, String)], name: &str) -> Option<&'a str> {
592 versions
593 .iter()
594 .find(|(candidate, _)| *candidate == name)
595 .map(|(_, version)| version.as_str())
596 }
597}