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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! System support functions.

use anyhow::Context;
use nix::errno;
use nix::sys::signal;
use tracing::trace;

#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))]
pub fn adjust_rlimits() {
    trace!("rlimit crate does not support this OS; not adjusting nofile limit");
}

/// Attempts to increase the soft nofile rlimit to the maximum possible value.
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "ios"))]
pub fn adjust_rlimits() {
    use rlimit::Resource;
    use tracing::warn;

    // getrlimit/setrlimit can have surprisingly different behavior across
    // platforms, even with the rlimit wrapper crate that we use. This function
    // is chattier than normal at the trace log level in an attempt to ease
    // debugging of such differences.

    let (soft, hard) = match Resource::NOFILE.get() {
        Ok(limits) => limits,
        Err(e) => {
            trace!("unable to read initial nofile rlimit: {}", e);
            return;
        }
    };
    trace!("initial nofile rlimit: ({}, {})", soft, hard);

    #[cfg(target_os = "macos")]
    let hard = {
        use std::cmp;

        use mz_ore::result::ResultExt;
        use sysctl::Sysctl;

        // On macOS, getrlimit by default reports that the hard limit is
        // unlimited, but there is usually a stricter hard limit discoverable
        // via sysctl. Failing to discover this secret stricter hard limit will
        // cause the call to setrlimit below to fail.
        let res = sysctl::Ctl::new("kern.maxfilesperproc")
            .and_then(|ctl| ctl.value())
            .map_err_to_string_with_causes()
            .and_then(|v| match v {
                sysctl::CtlValue::Int(v) => u64::try_from(v)
                    .map_err(|_| format!("kern.maxfilesperproc unexpectedly negative: {}", v)),
                o => Err(format!("unexpected sysctl value type: {:?}", o)),
            });
        match res {
            Ok(v) => {
                trace!("sysctl kern.maxfilesperproc hard limit: {}", v);
                cmp::min(v, hard)
            }
            Err(e) => {
                trace!("error while reading sysctl: {}", e);
                hard
            }
        }
    };

    trace!("attempting to adjust nofile rlimit to ({0}, {0})", hard);
    if let Err(e) = Resource::NOFILE.set(hard, hard) {
        trace!("error adjusting nofile rlimit: {}", e);
        return;
    }

    // Check whether getrlimit reflects the limit we installed with setrlimit.
    // Some platforms will silently ignore invalid values in setrlimit.
    let (soft, hard) = match Resource::NOFILE.get() {
        Ok(limits) => limits,
        Err(e) => {
            trace!("unable to read adjusted nofile rlimit: {}", e);
            return;
        }
    };
    trace!("adjusted nofile rlimit: ({}, {})", soft, hard);

    const RECOMMENDED_SOFT: u64 = 1024;
    if soft < RECOMMENDED_SOFT {
        warn!(
            "soft nofile rlimit ({}) is dangerously low; at least {} is recommended",
            soft, RECOMMENDED_SOFT
        )
    }
}

pub fn enable_sigusr2_coverage_dump() -> Result<(), anyhow::Error> {
    let action = signal::SigAction::new(
        signal::SigHandler::Handler(handle_sigusr2_signal),
        signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK,
        signal::SigSet::empty(),
    );

    unsafe { signal::sigaction(signal::SIGUSR2, &action) }
        .context("failed to install SIGUSR2 handler")?;

    Ok(())
}

pub fn enable_termination_signal_cleanup() -> Result<(), anyhow::Error> {
    let action = signal::SigAction::new(
        signal::SigHandler::Handler(handle_termination_signal),
        signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK,
        signal::SigSet::empty(),
    );

    for signum in &[
        signal::SIGHUP,
        signal::SIGINT,
        signal::SIGALRM,
        signal::SIGTERM,
        signal::SIGUSR1,
    ] {
        unsafe { signal::sigaction(*signum, &action) }
            .with_context(|| format!("failed to install handler for {}", signum))?;
    }

    Ok(())
}

extern "C" {
    fn __llvm_profile_write_file() -> libc::c_int;
}

extern "C" fn handle_sigusr2_signal(_: i32) {
    let _ = unsafe { __llvm_profile_write_file() };
}

extern "C" fn handle_termination_signal(signum: i32) {
    let _ = unsafe { __llvm_profile_write_file() };

    let action = signal::SigAction::new(
        signal::SigHandler::SigDfl,
        signal::SaFlags::SA_NODEFER | signal::SaFlags::SA_ONSTACK,
        signal::SigSet::empty(),
    );
    unsafe { signal::sigaction(signum.try_into().unwrap(), &action) }
        .unwrap_or_else(|_| panic!("failed to uninstall handler for {}", signum));

    let ret = unsafe { libc::raise(signum) };
    if ret == -1 {
        let errno = errno::from_i32(errno::errno());
        panic!("failed to re-raise signal {}: {}", signum, errno);
    }
}