rummage 0.2.0

A simple and opinionated environment collector
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#![doc = include_str!("../README.md")]

use std::collections::BTreeMap;
use std::path::PathBuf;
use tracing::Level;

pub use tracing;

#[cfg(feature = "serde")]
use serde::Serialize;

#[doc(hidden)]
#[cfg(feature = "git-version")]
pub use git_version::git_version;

#[cfg(not(feature = "git-version"))]
#[macro_export]
macro_rules! git_version {
    (
        $( args = [ $( $arg:literal ),* $(,)? ])?
    ) => {
        "rummage-rs built without the 'git-version' feature"
    };
}

/// Information about the crate that contains the [`info!`] invocation
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct CrateInfo {
    /// The full SHA256 commit hash of the git repository
    pub git_commit_hash: String,

    /// Whether the git repository is in a dirty state / has uncommitted modifications
    pub is_git_repo_dirty: bool,

    /// The name of the binary that the crate that has the [`info!`] invocation is being built into
    pub bin_name: String,
    pub crate_name: String,
    pub crate_version: String,
}

impl CrateInfo {
    #[doc(hidden)]
    pub fn new(git_version: &str, crate_name: &str, crate_version: &str, bin_name: &str) -> Self {
        let dirty = git_version.ends_with("-dirty");
        let hash = git_version.trim_end_matches("-dirty");

        Self {
            git_commit_hash: hash.to_string(),
            is_git_repo_dirty: dirty,
            crate_name: crate_name.to_string(),
            crate_version: crate_version.to_string(),
            bin_name: bin_name.to_string(),
        }
    }

    pub fn iter_props(&self) -> impl Iterator<Item = (&'static str, String)> {
        [
            ("git_commit_hash", self.git_commit_hash.clone()),
            ("git_repo_dirty", self.is_git_repo_dirty.to_string()),
            ("crate_name", self.crate_name.clone()),
            ("crate_version", self.crate_version.clone()),
            ("bin_name", self.bin_name.clone()),
        ]
        .into_iter()
    }

    fn log_debug(&self) {
        tracing::event!(
            Level::DEBUG,
            git_commit_hash = self.git_commit_hash,
            git_repo_dirty = self.is_git_repo_dirty,
            crate_name = self.crate_name,
            crate_version = self.crate_version,
            bin_name = self.bin_name,
            "Crate information:"
        );
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! _crate_info {
    () => {{
        ::rummage::CrateInfo::new(
            ::rummage::git_version!(
                args = [
                    "--always",
                    "--abbrev=0",
                    "--match",
                    "NOT A TAG",
                    "--dirty=-dirty"
                ]
            ),
            option_env!("CARGO_CRATE_NAME").unwrap_or("<failed to scrape>"),
            option_env!("CARGO_PKG_VERSION").unwrap_or("<failed to scrape>"),
            option_env!("CARGO_BIN_NAME").unwrap_or("<failed to scrape>"),
        )
    }};
}

/// How Cargo was configured while building the crate containing the crate containing the [`info!`]
/// invocation
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct CargoTarget {
    /// Typically either "debug" or "release"
    pub profile: String,

    /// The target triple of the environment performing the compilation
    pub host: String,

    /// The target triple of the environment the built artifact is intended for
    pub target: String,

    /// The "family" of the target, eg "unix"
    pub family: String,

    /// The specific OS within the target family, eg "linux"
    pub os: String,

    /// The CPU architecture of the target, eg "x86_64"
    pub arch: String,

    /// The number of bits in a pointer on the target platform, eg "64".
    pub pointer_width: String,

    /// The endianness of the target platform, eg "little"
    pub endian: String,

    /// A comma separated list of the features of the target platform that the compilation is
    /// using, eg "fxsr,sse,sse2"
    pub features: String,
}

impl CargoTarget {
    /// This method only works when called from within the rummage crate, as it relies on cargo
    /// environment variables rummage sets in its own build.rs
    fn gather() -> Self {
        Self {
            profile: env!("RUMMAGE_PROFILE").to_string(),
            host: env!("RUMMAGE_HOST").to_string(),
            target: env!("RUMMAGE_TARGET").to_string(),
            family: env!("RUMMAGE_CARGO_CFG_TARGET_FAMILY").to_string(),
            os: env!("RUMMAGE_CARGO_CFG_TARGET_OS").to_string(),
            arch: env!("RUMMAGE_CARGO_CFG_TARGET_ARCH").to_string(),
            pointer_width: env!("RUMMAGE_CARGO_CFG_TARGET_POINTER_WIDTH").to_string(),
            endian: env!("RUMMAGE_CARGO_CFG_TARGET_ENDIAN").to_string(),
            features: env!("RUMMAGE_CARGO_CFG_TARGET_FEATURE").to_string(),
        }
    }

    pub fn iter_props(&self) -> impl Iterator<Item = (&'static str, String)> {
        [
            ("profile", self.profile.clone()),
            ("host", self.host.clone()),
            ("target", self.target.clone()),
            ("family", self.family.clone()),
            ("os", self.os.clone()),
            ("arch", self.arch.clone()),
            ("pointer_width", self.pointer_width.clone()),
            ("endian", self.endian.clone()),
            ("features", self.features.clone()),
        ]
        .into_iter()
    }

    pub fn log_debug(&self) {
        tracing::event!(
            Level::DEBUG,
            profile = self.profile,
            host = self.host,
            target = self.target,
            family = self.family,
            os = self.os,
            arch = self.arch,
            pointer_width = self.pointer_width,
            endian = self.endian,
            features = self.features,
            "Cargo target information:"
        )
    }
}

/// Details about the version of rustc that built this crate
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct RustcVersion {
    pub rustc_semver: String,
    pub commit_hash: String,
    pub commit_date: String,
    pub llvm_version: String,
}

impl RustcVersion {
    /// This method only works when called from within the rummage crate, as it relies on cargo
    /// environment variables rummage sets in its own build.rs
    fn gather() -> Self {
        let major = env!("RUMMAGE_RUSTC_VERSION_MAJOR");
        let minor = env!("RUMMAGE_RUSTC_VERSION_MINOR");
        let patch = env!("RUMMAGE_RUSTC_VERSION_PATCH");
        let pre = env!("RUMMAGE_RUSTC_VERSION_PRE");
        let build = env!("RUMMAGE_RUSTC_VERSION_BUILD");

        let mut rustc_semver = format!("{major}.{minor}.{patch}");
        if !pre.is_empty() {
            rustc_semver.push('-');
            rustc_semver.push_str(pre);
        }

        if !build.is_empty() {
            rustc_semver.push('+');
            rustc_semver.push_str(build);
        }

        Self {
            rustc_semver,
            commit_hash: env!("RUMMAGE_RUSTC_VERSION_COMMIT_HASH").to_string(),
            commit_date: env!("RUMMAGE_RUSTC_VERSION_COMMIT_DATE").to_string(),
            llvm_version: env!("RUMMAGE_RUSTC_VERSION_LLVM_VERSION").to_string(),
        }
    }

    pub fn iter_props(&self) -> impl Iterator<Item = (&'static str, String)> {
        [
            ("rustc_semver", self.rustc_semver.clone()),
            ("commit_hash", self.commit_hash.clone()),
            ("commit_date", self.commit_date.clone()),
            ("llvm_version", self.llvm_version.clone()),
        ]
        .into_iter()
    }

    pub fn log_debug(&self) {
        tracing::event!(
            Level::DEBUG,
            rustc_semver = self.rustc_semver,
            commit_hash = self.commit_hash,
            commit_date = self.commit_date,
            llvm_version = self.llvm_version,
            "Rustc information:"
        );
    }
}

#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct CompileInfo {
    pub target: CargoTarget,
    pub rustc: RustcVersion,
}

impl CompileInfo {
    #[doc(hidden)]
    pub fn gather() -> Self {
        Self {
            target: CargoTarget::gather(),
            rustc: RustcVersion::gather(),
        }
    }

    pub fn log_debug(&self) {
        self.target.log_debug();
        self.rustc.log_debug();
    }
}

/// Runtime information about the system actually running the binary
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct SystemInfo {
    pub hostname: Option<String>,
    pub os: String,
    pub linux_distro: Option<String>,
    pub cpu_vendor: Option<String>,
    pub cpu_brand_string: Option<String>,
    pub num_cpus: usize,
    pub num_physical_cpus: usize,
}

impl SystemInfo {
    #[doc(hidden)]
    pub fn gather() -> Self {
        let os = sys_info::os_type()
            .and_then(|ty| sys_info::os_release().map(|rel| (ty, rel)))
            .map(|(ty, rel)| format!("{ty} {rel}"))
            .unwrap_or("<failed to query OS information>".to_string());

        let linux_distro = sys_info::linux_os_release()
            .ok()
            .and_then(|r| r.pretty_name);

        let cpu_vendor;
        let cpu_brand_string;

        #[cfg(target_arch = "x86_64")]
        {
            let cpuid = raw_cpuid::CpuId::new();
            cpu_vendor = cpuid.get_vendor_info().map(|v| v.as_str().to_string());
            cpu_brand_string = cpuid
                .get_processor_brand_string()
                .map(|s| s.as_str().to_string());
        }

        #[cfg(not(target_arch = "x86_64"))]
        {
            cpu_vendor = None;
            cpu_brand_string = None;
        }

        let num_cpus = num_cpus::get();
        let num_physical_cpus = num_cpus::get_physical();

        Self {
            hostname: sys_info::hostname().ok(),
            os,
            linux_distro,
            cpu_vendor,
            cpu_brand_string,
            num_cpus,
            num_physical_cpus,
        }
    }

    pub fn iter_props(&self) -> impl Iterator<Item = (&'static str, String)> {
        [
            ("hostname", self.hostname.clone().unwrap_or_default()),
            ("os", self.os.clone()),
            (
                "linux_distro",
                self.linux_distro.clone().unwrap_or_default(),
            ),
            ("cpu_vendor", self.cpu_vendor.clone().unwrap_or_default()),
            (
                "cpu_brand_string",
                self.cpu_brand_string.clone().unwrap_or_default(),
            ),
            ("num_cpus", self.num_cpus.to_string()),
            ("num_physical_cpus", self.num_physical_cpus.to_string()),
        ]
        .into_iter()
    }

    pub fn log_debug(&self) {
        fn map_optional_string(s: &Option<String>) -> &str {
            s.as_ref().map(|s| s.as_str()).unwrap_or("<failed to get>")
        }

        tracing::event!(
            Level::DEBUG,
            hostname = map_optional_string(&self.hostname),
            os = self.os,
            linux_distro = map_optional_string(&self.linux_distro),
            cpu_vendor = map_optional_string(&self.cpu_vendor),
            cpu_brand_string = map_optional_string(&self.cpu_brand_string),
            num_cpus = self.num_cpus,
            num_physical_cpus = self.num_physical_cpus,
            "System information:"
        )
    }
}

#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct RuntimeEnvironment {
    /// The full command line that this executable was invoked with
    pub command_line: Vec<String>,

    /// The working directory of the program when the [`info!`] macro was invoked
    pub working_dir: Option<PathBuf>,

    /// A list of the CPU core IDs that this process has in its affinity mask,
    /// if it has an affinity mask at all
    pub core_affinity: Option<Vec<usize>>,

    /// Set of environment variables that have been explicitly gathered with
    /// [`RummageInfo::with_envvar`]/[`RummageInfo::with_envvars`].
    pub envvars: BTreeMap<String, Option<String>>,
}

/// A bitset representation of the CPU core affinity mask of the process
pub fn core_affinity_string(cores: &[usize]) -> String {
    let max = *cores.iter().max().unwrap_or(&0) + 1;

    // Round up to the nearest multiple of 8
    let max = (max + 7) & !7;

    let mut bitset = vec![false; max];
    for id in cores {
        bitset[max - *id - 1] = true;
    }

    let mut string = String::with_capacity(max + max / 4);
    for nibble in bitset.chunks(4) {
        for bit in nibble.iter() {
            string.push(if *bit { '1' } else { '0' });
        }
        string.push(' ');
    }
    string.pop();

    string
}

impl RuntimeEnvironment {
    pub fn new() -> Self {
        Self {
            command_line: std::env::args().collect(),
            working_dir: std::env::current_dir().ok(),
            core_affinity: core_affinity::get_core_ids()
                .map(|ids| ids.into_iter().map(|id| id.id).collect()),
            envvars: BTreeMap::new(),
        }
    }

    /// Enriches the content of this [`RummageInfo`] with the value of the given environment
    /// variable
    pub fn with_envvar(mut self, name: impl AsRef<str>) -> Self {
        let name = name.as_ref().to_string();
        let value = std::env::var(&name).ok();
        self.envvars.insert(name, value);
        self
    }

    /// Enrichves the content of this [`RummageInfo`] with the values of all the given environment
    /// variables
    pub fn with_envvars(mut self, names: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        for name in names {
            self = self.with_envvar(name);
        }
        self
    }

    pub fn iter_props(&self) -> impl Iterator<Item = (&'static str, String)> + '_ {
        let working_dir = self
            .working_dir
            .as_ref()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or("<failed to get>".to_string());

        let core_affinity_string = match &self.core_affinity {
            Some(cores) => core_affinity_string(cores),
            None => "<not set>".to_string(),
        };

        [
            ("working_dir", working_dir),
            ("command_line_tokenized", format!("{:?}", self.command_line)),
            ("command_line_raw", self.command_line.join(" ")),
            ("core_affinity", core_affinity_string),
        ]
        .into_iter()
    }

    pub fn log_debug(&self) {
        tracing::event!(
            Level::DEBUG,
            args = format!("{:?}", self.command_line),
            "Command line args:"
        );

        tracing::event!(
            Level::DEBUG,
            working_dir = format!("{:?}", self.working_dir),
            "Working directory:"
        );
        
        let core_affinity_string = match &self.core_affinity {
            Some(cores) => core_affinity_string(cores),
            None => "<not set>".to_string(),
        };

        tracing::event!(
            Level::DEBUG,
            core_affinity = core_affinity_string,
            "Core affinity:"
        );

        tracing::event!(
            Level::DEBUG,
            args = format!("{:?}", self.envvars),
            "Environment variables:"
        );
    }
}

/// Top level info struct returned by [`info!`]
///
/// Example usage:
/// ```
/// rummage::info!()
///     .with_envvars(["RUST_LOG", "HOME", "MY_ENVVAR"])
///     .log_debug();
/// ```
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug)]
pub struct RummageInfo {
    /// Information about the crate that contains the [`info!()`] invocation
    pub crate_info: CrateInfo,

    /// Information about the compilation process
    ///
    /// Specifically, this is information about how `rummage` itself was compiled. In Cargo's
    /// default configuration this will also be the same as the target crate being built, though it
    /// is possible to override this behavior in some circumstances, eg to build dependencies with
    /// the release profile even when the target crate is being built under the debug profile.
    pub compile_info: CompileInfo,

    /// Information about the system that the program is running on
    pub system_info: SystemInfo,

    /// Properties of the environment the program is currently being run in
    pub runtime_env: RuntimeEnvironment,
}

impl RummageInfo {
    pub fn with_envvar(mut self, name: impl AsRef<str>) -> Self {
        self.runtime_env = self.runtime_env.with_envvar(name);
        self
    }

    pub fn with_envvars(mut self, names: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        self.runtime_env = self.runtime_env.with_envvars(names);
        self
    }

    /// Emits the contained information as [`tracing`] events, at the DEBUG level
    pub fn log_debug(&self) {
        self.crate_info.log_debug();
        self.compile_info.log_debug();
        self.system_info.log_debug();
        self.runtime_env.log_debug();
    }
}

/// Build a [`RummageInfo`] struct containing all of the standard infomation sets
///
/// Needs to be a macro, as some information depends on which crate is actually executing the code.
/// If it were a regular function call, properties such as crate name/version would always just
/// refer to the build of `rummage` itself rather than the crate being instrumented.
#[macro_export]
macro_rules! info {
    () => {{
        ::rummage::RummageInfo {
            crate_info: ::rummage::_crate_info!(),
            compile_info: ::rummage::CompileInfo::gather(),
            system_info: ::rummage::SystemInfo::gather(),
            runtime_env: ::rummage::RuntimeEnvironment::new(),
        }
    }};
}

#[macro_export]
macro_rules! log_all {
    ($info:expr) => {
        $crate::log_all!($info, level = $crate::tracing::Level::INFO)
    };

    ($info:expr, level=$level:expr) => {{
        use $crate::tracing::event;

        event!($level, "Collected rummage info:");

        event!($level, "    Crate info:");
        for (prop, value) in $info.crate_info.iter_props() {
            event!($level, "    {:>25}: {}", prop, value);
        }

        event!($level, "");
        event!($level, "    Compilation target:");
        for (prop, value) in $info.compile_info.target.iter_props() {
            event!($level, "    {:>25}: {}", prop, value);
        }

        event!($level, "");
        event!($level, "    Rustc version:");
        for (prop, value) in $info.compile_info.rustc.iter_props() {
            event!($level, "    {:>25}: {}", prop, value);
        }

        event!($level, "");
        event!($level, "    System info:");
        for (prop, value) in $info.system_info.iter_props() {
            event!($level, "    {:>25}: {}", prop, value);
        }

        event!($level, "");
        event!($level, "    Runtime environment:");
        for (prop, value) in $info.runtime_env.iter_props() {
            event!($level, "    {:>25}: {}", prop, value);
        }

        event!($level, "");
        event!($level, "    Environment variables:");
        for (name, value) in $info.runtime_env.envvars.iter() {
            event!(
                $level,
                "        {}={}",
                name,
                value.as_deref().unwrap_or("")
            );
        }
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cpu_affinity_string() {
        assert_eq!(core_affinity_string(&[0]), "0000 0001");
        assert_eq!(core_affinity_string(&[1]), "0000 0010");
        assert_eq!(core_affinity_string(&[7]), "1000 0000");
        assert_eq!(core_affinity_string(&[0, 1]), "0000 0011");
        assert_eq!(core_affinity_string(&[0, 1, 2, 3]), "0000 1111");
        assert_eq!(core_affinity_string(&[0, 1, 2, 3, 4, 5, 6, 7]), "1111 1111");
        assert_eq!(core_affinity_string(&[8]), "0000 0001 0000 0000");
    }
}