Files
adler32
ahash
aho_corasick
ansi_term
antidote
anyhow
arc_swap
arrayvec
async_speed_limit
async_stream
async_stream_impl
async_trait
atty
aws
backtrace
backtrace_sys
backup
base64
batch_system
bitfield
bitflags
block_buffer
boolinator
bstr
byteorder
bytes
bzip2_sys
cargo_metadata
cdc
cfg_if
chrono
chrono_tz
clap
cloud
codec
collections
concurrency_manager
configuration
configuration_derive
const_fn
const_random
const_random_macro
coprocessor_plugin_api
cpuid_bool
crc32fast
crc64fast
crossbeam
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_skiplist
crossbeam_utils
crypto_mac
darling
darling_core
darling_macro
dashmap
debugid
derive_more
digest
dirs
dirs_sys
doc_comment
dtoa
either
encoding_rs
encryption
encryption_export
engine_panic
engine_rocks
engine_test
engine_traits
engine_traits_tests
error_code
error_code_gen
example_plugin
external_storage
external_storage_export
fail
failure
failure_derive
farmhash
file_system
filetime
flate2
fnv
foreign_types
foreign_types_shared
fs2
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_timer
futures_util
async_await
compat
future
io
lock
sink
stream
task
fuzz
fxhash
gcp
generic_array
getrandom
getset
grpcio
grpcio_health
grpcio_sys
h2
heck
hex
hmac
http
http_body
httparse
httpdate
hyper
hyper_openssl
hyper_tls
ident_case
idna
indexmap
inferno
inotify
inotify_sys
instant
into_other
iovec
ipnet
ipnetwork
itertools
itoa
keys
kvproto
lazy_static
lazycell
libc
libflate
libflate_lz77
libloading
librocksdb_sys
libtitan_sys
libz_sys
linked_hash_map
linked_hash_set
lock_api
log
log_wrappers
lz4_sys
match_template
matches
md5
memchr
memmap
memoffset
memory_trace_macros
mime
mime_guess
mio
mio_extras
mio_uds
more_asserts
murmur3
native_tls
net2
nix
nodrop
nom
notify
num
num_complex
num_cpus
num_derive
num_format
num_integer
num_iter
num_rational
num_traits
once_cell
opaque_debug
openssl
openssl_probe
openssl_sys
ordered_float
panic_hook
parking_lot
parking_lot_core
paste
paste_impl
pd_client
percent_encoding
pest
pin_project
pin_project_lite
pin_utils
pnet_base
pnet_datalink
pnet_sys
pprof
ppv_lite86
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
procfs
procinfo
profiler
prometheus
prometheus_static_metric
promptly
prost
prost_derive
protobuf
quick_xml
quote
raft
raft_engine
raft_log_engine
raft_proto
raftstore
rand
rand_chacha
rand_core
rand_isaac
rayon
rayon_core
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
resolved_ts
rev_lines
rgb
ring
rle_decode_fast
rocksdb
rusoto_core
rusoto_credential
rusoto_kms
rusoto_s3
rusoto_signature
rusoto_sts
rustc_demangle
rustyline
ryu
safemem
same_file
scopeguard
security
semver
semver_parser
serde
serde_derive
serde_ignored
serde_json
serde_urlencoded
serde_with
serde_with_macros
server
sha2
shlex
signal
signal_hook_registry
slab
slog
slog_async
slog_derive
slog_global
slog_json
slog_term
smallvec
snappy_sys
socket2
spin
sst_importer
stable_deref_trait
standback
static_assertions
str_stack
strsim
structopt
structopt_derive
strum
strum_macros
subtle
symbolic_common
symbolic_demangle
syn
syn_mid
synstructure
sysinfo
take_mut
tame_gcs
tame_oauth
tempfile
term
test_backup
test_coprocessor
test_pd
test_raftstore
test_sst_importer
test_storage
test_util
textwrap
thiserror
thiserror_impl
thread_local
tidb_query_aggr
tidb_query_codegen
tidb_query_common
tidb_query_datatype
tidb_query_executors
tidb_query_expr
tikv
coprocessor
coprocessor_v2
import
server
storage
tikv_alloc
tikv_ctl
tikv_jemalloc_ctl
tikv_jemalloc_sys
tikv_jemallocator
tikv_kv
tikv_server
tikv_util
time
time_macros
time_macros_impl
tipb
tipb_helper
tokio
fs
future
io
loom
macros
net
park
process
runtime
signal
stream
sync
task
time
util
tokio_executor
tokio_macros
tokio_openssl
tokio_timer
tokio_tls
tokio_util
toml
tower_service
tracing
tracing_core
try_lock
twoway
twox_hash
txn_types
typenum
ucd_trie
unchecked_index
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
untrusted
url
utf8parse
uuid
vec_map
vlog
walkdir
want
xml
yatp
zeroize
zstd_sys
  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
//! Process resource limit information from `/proc/[pid]/limits`.

use std::fs::File;
use std::io::Result;
use std::time::Duration;

use libc::pid_t;
use nom::{
    IResult,
    space,
};

use parsers::{
    map_result,
    parse_u64,
    parse_usize,
    read_to_end
};

fn parse_limit<'a, P, T>(input: &'a [u8], value_parser: P) -> IResult<&'a [u8], Limit<T>>
where P: Fn(&[u8]) -> IResult<&[u8], T> {
    let parse_field = closure!(&'a [u8], alt!(
         tag!("unlimited") => { |_| None }
       | value_parser => { |value| Some(value) }
    ));

    map!(input, separated_pair!(parse_field, space, parse_field),
         |(soft, hard)| Limit { soft: soft, hard: hard })
}

fn duration_from_micros(micros: u64) -> Duration {
    let micros_per_sec = 1_000_000;
    let nanos_per_micro = 1000;
    let secs = micros / micros_per_sec;
    let nanos = ((micros % micros_per_sec) as u32) * nanos_per_micro;
    Duration::new(secs, nanos)
}

named!(parse_limit_usize( &[u8] ) -> Limit<usize>, apply!(parse_limit, parse_usize));
named!(parse_limit_u64( &[u8] ) -> Limit<u64>, apply!(parse_limit, parse_u64));
named!(parse_limit_seconds( &[u8] ) -> Limit<Duration>,
       map!(apply!(parse_limit, parse_u64),
            | Limit { soft, hard } | {
                Limit {
                    soft: soft.map(Duration::from_secs),
                    hard: hard.map(Duration::from_secs),
                }
            }
       ));
named!(parse_limit_micros( &[u8] ) -> Limit<Duration>,
       map!(apply!(parse_limit, parse_u64),
            | Limit { soft, hard } | {
                Limit {
                    soft: soft.map(duration_from_micros),
                    hard: hard.map(duration_from_micros),
                }
            }
       ));

named!(parse_limits( &[u8] ) -> Limits,
    ws!(do_parse!(
        tag!("Limit") >> tag!("Soft Limit") >> tag!("Hard Limit") >> tag!("Units") >>
        tag!("Max cpu time")          >> max_cpu_time: parse_limit_seconds        >> tag!("seconds")    >>
        tag!("Max file size")         >> max_file_size: parse_limit_u64           >> tag!("bytes")      >>
        tag!("Max data size")         >> max_data_size: parse_limit_usize         >> tag!("bytes")      >>
        tag!("Max stack size")        >> max_stack_size: parse_limit_usize        >> tag!("bytes")      >>
        tag!("Max core file size")    >> max_core_file_size: parse_limit_usize    >> tag!("bytes")      >>
        tag!("Max resident set")      >> max_resident_set: parse_limit_usize      >> tag!("bytes")      >>
        tag!("Max processes")         >> max_processes: parse_limit_usize         >> tag!("processes")  >>
        tag!("Max open files")        >> max_open_files: parse_limit_usize        >> tag!("files")      >>
        tag!("Max locked memory")     >> max_locked_memory: parse_limit_usize     >> tag!("bytes")      >>
        tag!("Max address space")     >> max_address_space: parse_limit_usize     >> tag!("bytes")      >>
        tag!("Max file locks")        >> max_file_locks: parse_limit_usize        >> tag!("locks")      >>
        tag!("Max pending signals")   >> max_pending_signals: parse_limit_usize   >> tag!("signals")    >>
        tag!("Max msgqueue size")     >> max_msgqueue_size: parse_limit_usize     >> tag!("bytes")      >>
        tag!("Max nice priority")     >> max_nice_priority: parse_limit_usize     >>
        tag!("Max realtime priority") >> max_realtime_priority: parse_limit_usize >>
        tag!("Max realtime timeout")  >> max_realtime_timeout: parse_limit_micros >> tag!("us")         >>
        (Limits {
            max_cpu_time: max_cpu_time,
            max_file_size: max_file_size,
            max_data_size: max_data_size,
            max_stack_size: max_stack_size,
            max_core_file_size: max_core_file_size,
            max_resident_set: max_resident_set,
            max_processes: max_processes,
            max_open_files: max_open_files,
            max_locked_memory: max_locked_memory,
            max_address_space: max_address_space,
            max_file_locks: max_file_locks,
            max_pending_signals: max_pending_signals,
            max_msgqueue_size: max_msgqueue_size,
            max_nice_priority: max_nice_priority,
            max_realtime_priority: max_realtime_priority,
            max_realtime_timeout: max_realtime_timeout,
        })
    ))
);

/// A resource limit, including a soft and hard bound.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Limit<T> {
    /// The soft resource limit.
    ///
    /// The kernel enforces that resource usage does not exceed this value.
    pub soft: Option<T>,

    /// The hard resource limit.
    ///
    /// The kernel allows the soft limit to be raised until this limit using
    /// `setrlimit`.
    pub hard: Option<T>,
}

/// Process limits information
/// See `man 2 getrlimit`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Limits {
    /// The maximum CPU time a process can use.
    pub max_cpu_time: Limit<Duration>,
    /// The maximum size of files that the process may create in bytes.
    pub max_file_size: Limit<u64>,
    /// The maximum size of the process's data segment in bytes.
    pub max_data_size: Limit<usize>,
    /// The maximum size of the process stack in bytes.
    pub max_stack_size: Limit<usize>,
    /// Maximum size of a core file in bytes.
    pub max_core_file_size: Limit<usize>,
    /// Specifies the limit of the process's resident set in bytes.
    pub max_resident_set: Limit<usize>,
    /// The maximum number of processes (or, more precisely on Linux, threads)
    /// that can be created for the real user ID of the calling process.
    pub max_processes: Limit<usize>,
    /// Specifies a value one greater than the maximum file descriptor
    /// number that can be opened by this process.
    pub max_open_files: Limit<usize>,
    /// The maximum number of bytes of memory that may be locked into RAM.
    pub max_locked_memory: Limit<usize>,
    /// The maximum size of the process's virtual memory (address space) in bytes.
    pub max_address_space: Limit<usize>,
    /// A limit on the combined number of locks and leases that this process may
    /// establish.
    pub max_file_locks: Limit<usize>,
    /// Specifies the limit on the number of signals that may be queued for the
    /// real user ID of the calling process.
    pub max_pending_signals: Limit<usize>,
    /// Specifies the limit on the number of bytes that can be allocated for
    /// POSIX message queues for the real user ID of the calling process.
    pub max_msgqueue_size: Limit<usize>,
    /// Specifies a ceiling to which the process's nice value can be raised.
    pub max_nice_priority: Limit<usize>,
    /// Specifies a limit on the amount of CPU time that a process scheduled
    /// under a real-time scheduling policy may consume without making a blocking
    /// system call.
    pub max_realtime_priority: Limit<usize>,
    /// Specifies a ceiling on the real-time priority that may be set for this process.
    pub max_realtime_timeout: Limit<Duration>,
}

/// Parses the provided limits file.
fn limits_file(file: &mut File) -> Result<Limits> {
    let mut buf = [0; 2048]; // A typical limits file is about 1350 bytes
    map_result(parse_limits(try!(read_to_end(file, &mut buf))))
}

/// Returns resource limit information from the process with the provided pid.
pub fn limits(pid: pid_t) -> Result<Limits> {
    limits_file(&mut try!(File::open(&format!("/proc/{}/limits", pid))))
}

/// Returns resource limit information for the current process.
pub fn limits_self() -> Result<Limits> {
    limits_file(&mut try!(File::open("/proc/self/limits")))
}

/// Returns resource limit information from the thread with the provided parent process ID and thread ID.
pub fn limits_task(process_id: pid_t, thread_id: pid_t) -> Result<Limits> {
    limits_file(&mut try!(File::open(&format!("/proc/{}/task/{}/limits", process_id, thread_id))))
}

#[cfg(test)]
pub mod tests {

    use std::time::Duration;

    use parsers::tests::unwrap;
    use super::{limits, limits_self, parse_limits};

    /// Test that the system limit file can be parsed.
    #[test]
    fn test_limits() {
        limits_self().unwrap();
        limits(1).unwrap();
    }

    #[test]
    fn test_parse_limits() {
        let text = b"Limit                     Soft Limit           Hard Limit           Units         \n
                     Max cpu time              10                   60                   seconds       \n
                     Max file size             unlimited            unlimited            bytes         \n
                     Max data size             unlimited            unlimited            bytes         \n
                     Max stack size            8388608              unlimited            bytes         \n
                     Max core file size        unlimited            unlimited            bytes         \n
                     Max resident set          unlimited            unlimited            bytes         \n
                     Max processes             63632                63632                processes     \n
                     Max open files            1024                 4096                 files         \n
                     Max locked memory         65536                65536                bytes         \n
                     Max address space         unlimited            unlimited            bytes         \n
                     Max file locks            unlimited            unlimited            locks         \n
                     Max pending signals       63632                63632                signals       \n
                     Max msgqueue size         819200               819200               bytes         \n
                     Max nice priority         0                    0                                  \n
                     Max realtime priority     0                    0                                  \n
                     Max realtime timeout      500                  unlimited            us            \n";

        let limits = unwrap(parse_limits(text));

        assert_eq!(Some(Duration::new(10, 0)), limits.max_cpu_time.soft);
        assert_eq!(Some(Duration::new(60, 0)), limits.max_cpu_time.hard);

        assert_eq!(None, limits.max_file_size.soft);
        assert_eq!(None, limits.max_file_size.hard);

        assert_eq!(None, limits.max_data_size.soft);
        assert_eq!(None, limits.max_data_size.hard);

        assert_eq!(Some(8388608), limits.max_stack_size.soft);
        assert_eq!(None, limits.max_stack_size.hard);

        assert_eq!(None, limits.max_core_file_size.soft);
        assert_eq!(None, limits.max_core_file_size.hard);

        assert_eq!(None, limits.max_resident_set.soft);
        assert_eq!(None, limits.max_resident_set.hard);

        assert_eq!(Some(63632), limits.max_processes.soft);
        assert_eq!(Some(63632), limits.max_processes.hard);

        assert_eq!(Some(1024), limits.max_open_files.soft);
        assert_eq!(Some(4096), limits.max_open_files.hard);

        assert_eq!(Some(65536), limits.max_locked_memory.soft);
        assert_eq!(Some(65536), limits.max_locked_memory.hard);

        assert_eq!(None, limits.max_address_space.soft);
        assert_eq!(None, limits.max_address_space.hard);

        assert_eq!(None, limits.max_file_locks.soft);
        assert_eq!(None, limits.max_file_locks.hard);

        assert_eq!(Some(63632), limits.max_pending_signals.soft);
        assert_eq!(Some(63632), limits.max_pending_signals.hard);

        assert_eq!(Some(819200), limits.max_msgqueue_size.soft);
        assert_eq!(Some(819200), limits.max_msgqueue_size.hard);

        assert_eq!(Some(0), limits.max_nice_priority.soft);
        assert_eq!(Some(0), limits.max_nice_priority.hard);

        assert_eq!(Some(0), limits.max_realtime_priority.soft);
        assert_eq!(Some(0), limits.max_realtime_priority.hard);

        assert_eq!(Some(Duration::new(0, 500 * 1000)), limits.max_realtime_timeout.soft);
        assert_eq!(None, limits.max_realtime_timeout.hard);
    }
}

#[cfg(all(test, rustc_nightly))]
mod benches {
    extern crate test;

    use std::fs::File;

    use parsers::read_to_end;
    use super::*;

    #[bench]
    fn bench_limits(b: &mut test::Bencher) {
        b.iter(|| test::black_box(limits(1)));
    }

    #[bench]
    fn bench_limits_parse(b: &mut test::Bencher) {
        let mut buf = [0; 2048];
        let limits = read_to_end(&mut File::open("/proc/1/limits").unwrap(), &mut buf).unwrap();
        b.iter(|| test::black_box(parse_limits(limits)));
    }
}