xref: /spdk/scripts/core-collector.sh (revision fecffda6ecf8853b82edccde429b68252f0a62c5)
1#!/usr/bin/env bash
2#  SPDX-License-Identifier: BSD-3-Clause
3#  Copyright (C) 2020 Intel Corporation
4#  All rights reserved.
5#
6# We don't want to tell kernel to include %e or %E since these
7# can include whitespaces or other funny characters, and working
8# with those on the cmdline would be a nightmare. Use procfs for
9# the remaining pieces we want to gather:
10# |$rootdir/scripts/core-collector.sh %P %s %t %c $output_dir
11
12core_meta() {
13	jq . <<- CORE
14		{
15		  "$exe_comm": {
16		    "ts": "$core_time",
17		    "size": "$core_size bytes",
18		    "PID": $core_pid,
19		    "signal": "$core_sig ($core_sig_name)",
20		    "path": "$exe_path",
21		    "statm": "$statm"
22		  }
23		}
24	CORE
25}
26
27bt() { hash gdb && gdb -batch -ex "thread apply all bt full" "$1" "$2" 2>&1; }
28
29stderr() {
30	exec 2> "$core.stderr.txt"
31	set -x
32}
33
34args+=(core_pid)
35args+=(core_sig)
36args+=(core_ts)
37args+=(rlimit)
38
39read -r "${args[@]}" <<< "$*"
40
41exe_path=$(readlink -f "/proc/$core_pid/exe")
42exe_comm=$(< "/proc/$core_pid/comm")
43statm=$(< "/proc/$core_pid/statm")
44core_time=$(date -d@"$core_ts")
45core_sig_name=$(kill -l "$core_sig")
46
47core=$(< "${0%/*}/../.coredump_path")/${exe_path##*/}_$core_pid.core
48stderr
49
50# RLIMIT_CORE is not enforced when core is piped to us. To make
51# sure we won't attempt to overload underlying storage, copy
52# only the reasonable amount of bytes (systemd defaults to 2G
53# so let's follow that). But first, check limits of terminating
54# process to see if we need to make any adjustments.
55max_core=$((1024 * 1024 * 1024 * 2))
56
57if ((rlimit == 0xffffffffffffffff || rlimit > max_core)); then
58	rlimit=$max_core
59fi
60
61# Clear path for lz
62rm -f "$core"{,.{bin,bt,gz,json}}
63
64# Slurp the core
65head -c "$rlimit" <&0 > "$core"
66core_size=$(wc -c < "$core")
67
68# Compress it
69gzip -c "$core" > "$core.gz"
70
71# Save the binary
72cp "$exe_path" "$core.bin"
73
74# Save the backtrace
75bt "$exe_path" "$core" > "$core.bt.txt"
76
77# Save the metadata of the core
78core_meta > "$core.json"
79
80# Nuke the original core
81rm "$core"
82