Debian Codegraph @

contrib/scripts/ast_loggrabber

raw symbols SCIP
1 #!/usr/bin/env bash
2 # Turn on extended globbing
3 shopt -s extglob
4 # Bail on any error
5 set -e
6
7 prog=$(basename $0)
8
9 print_help() {
10 cat <<EOF
11 NAME
12 $prog - Gather asterisk log files
13
14 SYNOPSIS
15 $prog [ --help ] [ --dateformat="<dateformat>" ]
16 [ --timezone="<timezone>" ] [ --append-logfiles ]
17 [ --tarball-uniqueid="<uniqueid>" ]
18 [ <logfiles> | <pattern> ... ]
19
20 DESCRIPTION
21
22 Gathers log files, optionally converts POSIX timestamps
23 to readable format. and creates a tarball.
24
25 Options:
26
27 --help
28 Print this help.
29
30 --dateformat="<dateformat>"
31 A Python strftime format string to be used when converting
32 POSIX timestamps in log files to readable format. If not
33 specified as an argument or in the config file, no conversion
34 is done.
35
36 --timezone="<timezone>"
37 The timezone to use when converting POSIX timestamps to
38 readable format. It can be specified in "<continent>/<city>"
39 format or in abbreviation format such as "CST6CDT". If not
40 specified as an argument or in the config file, the "local"
41 timezone is used.
42
43 --append-logfiles
44 Append any log files specified on the command line to the
45 config file specified ones instead of overriding them.
46
47 --tarball-uniqueid="<uniqueid>"
48 Normally DATEFORMAT is used to make the tarballs unique
49 but you can use your own unique id in the tarball names
50 such as a Jira issue id.
51
52 <logfiles> | <pattern>
53 A list of log files or log file search patterns. Unless
54 --append-logfiles was specified, these entries will override
55 those specified in the config files.
56
57 If no files are specified on the command line the, value of
58 LOGFILES from ast_debug_tools.conf will be used. Failing
59 that, the following patterns will be used:
60 /var/log/asterisk/messages*
61 /var/log/asterisk/queue*
62 /var/log/asterisk/debug*
63 /var/log/asterisk/security*
64
65 NOTES
66 Any files output will have ':' characters changed to '-'. This is
67 to facilitate uploading those files to Jira which doesn't like the
68 colons.
69
70 FILES
71 /etc/asterisk/ast_debug_tools.conf
72 ~/ast_debug_tools.conf
73 ./ast_debug_tools.conf
74
75 # Readable Local time for the tarball names
76 DATEFORMAT='date +%FT%H-%M-%S%z'
77
78 # A list of log files and/or log file search patterns using the
79 # same syntax as COREDUMPS.
80 #
81 LOGFILES=(/var/log/asterisk/messages* /var/log/asterisk/queue* \\
82 /var/log/asterisk/debug* /var/log/asterisk/security*)
83
84 # $prog converts POSIX timestamps to readable format
85 # using this Python strftime format string. If not specified
86 # or an empty string, no format covnersion is done.
87 LOG_DATEFORMAT="%m/%d %H:%M:%S.%f"
88
89 # The timezone to use when converting POSIX timestamps to
90 # readable format. It can be specified in "<continent>/<city>"
91 # format or in abbreviation format such as "CST6CDT". If not
92 # specified, the "local" timezone is used.
93 # LOG_TIMEZONE=
94
95 EOF
96 exit 1
97 }
98
99 append_logfiles=false
100
101 declare -a LOGFILES
102 declare -a ARGS_LOGFILES
103
104 # Function to safely source a config file with security checks
105 # This prevents privilege escalation by ensuring config files are
106 # owned by root and not writable by group or others when running as root
107 safe_source_config() {
108 local config_file="$1"
109
110 # Return if file doesn't exist
111 [ -f "$config_file" ] || return 0
112
113 # Get the absolute path
114 config_file=$(readlink -f "$config_file")
115
116 # Check if running as root (effective UID is 0)
117 if [ $EUID -eq 0 ]; then
118 # Running as root - apply strict security checks
119 # Get file owner UID and permissions
120 local file_stat
121 file_stat=$(stat -c "%u %a" "$config_file" 2>/dev/null) || return 0
122 local owner_uid=${file_stat%% *}
123 local perms=${file_stat##* }
124
125 # File must be owned by root (UID 0)
126 if [ "$owner_uid" -ne 0 ]; then
127 echo "WARNING: Config file $config_file is not owned by root. Skipping for security." >&2
128 return 1
129 fi
130
131 # File must not be writable by group or others (check group-write and other-write bits)
132 # Extract the group and other permission digits
133 local group_perms=$((perms / 10 % 10))
134 local other_perms=$((perms % 10))
135
136 if [ $((group_perms & 2)) -ne 0 ] || [ $((other_perms & 2)) -ne 0 ]; then
137 echo "WARNING: Config file $config_file is writable by group or others. Skipping for security." >&2
138 return 1
139 fi
140 fi
141
142 source "$config_file"
143 }
144
145 # Read config files from least important to most important
146 safe_source_config /etc/asterisk/ast_debug_tools.conf
147 safe_source_config ~/ast_debug_tools.conf
148 safe_source_config ./ast_debug_tools.conf
149
150 if [ ${#LOGFILES[@]} -eq 0 ] ; then
151 LOGFILES+=(/var/log/asterisk/messages* /var/log/asterisk/queue* \
152 /var/log/asterisk/debug* /var/log/asterisk/security*)
153 fi
154
155 DATEFORMAT=${DATEFORMAT:-'date +%FT%H-%M-%S%z'}
156
157 # Use "$@" (with the quotes) so spaces in patterns or
158 # file names are preserved.
159 # Later on when we have to iterate over LOGFILES, we always
160 # use the indexes rather than trying to expand the values of LOGFILES
161 # just in case.
162
163 for a in "$@" ; do
164 case "$a" in
165 --dateformat=*)
166 LOG_DATEFORMAT=${a#*=}
167 ;;
168 --timezone=*)
169 LOG_TIMEZONE=${a#*=}
170 ;;
171 --append-logfiles)
172 append_logfiles=true
173 ;;
174 --tarball-uniqueid=*)
175 tarball_uniqueid=${a#*=}
176 ;;
177 --help|-*)
178 print_help
179 ;;
180 *)
181 ARGS_LOGFILES+=("$a")
182 # If any files are specified on the command line, ignore those
183 # specified in the config files unless append-logfiles was specified.
184 if ! $append_logfiles ; then
185 LOGFILES=()
186 fi
187 esac
188 done
189
190 # append logfiles/patterns specified as command line arguments to LOGFILES.
191 for i in ${!ARGS_LOGFILES[@]} ; do
192 LOGFILES+=("${ARGS_LOGFILES[$i]}")
193 done
194
195 # At this point, all glob entries that match files should be expanded.
196 # Any entries that don't exist are probably globs that didn't match anything
197 # and need to be pruned.
198
199 for i in ${!LOGFILES[@]} ; do
200 if [ ! -f "${LOGFILES[$i]}" ] ; then
201 unset LOGFILES[$i]
202 continue
203 fi
204 done
205
206 # Sort and weed out any dups
207 IFS=$'\x0a'
208 readarray -t LOGFILES < <(echo -n "${LOGFILES[*]}" | sort -u )
209 unset IFS
210
211 if [ "${#LOGFILES[@]}" -eq 0 ] ; then
212 echo "No log files found"
213 print_help
214 fi
215
216 # Timestamp to use for output files
217 df=${tarball_uniqueid:-$(${DATEFORMAT})}
218
219 tmpdir=$(mktemp -d)
220 if [ -z "$tmpdir" ] ; then
221 echo "${prog}: Unable to create temporary directory."
222 exit 1
223 fi
224
225 # Extract the Python timestamp conver script from the end of this
226 # script and save it to the temporary directory
227
228 install -m 0600 /dev/stdin "$tmpdir/.ast_tsconvert.py" < <(sed '1,/^#@@@SCRIPTSTART@@@/ d' "$0")
229
230 trap "rm -rf $tmpdir" EXIT
231 tardir=asterisk-${df}.logfiles
232
233 # Now iterate over the logfiles
234 for i in ${!LOGFILES[@]} ; do
235 lf=${LOGFILES[$i]}
236 destdir="$tmpdir/$tardir/$(dirname $lf)"
237 destfile="$tmpdir/$tardir/$lf"
238 mkdir -p "$destdir" 2>/dev/null || :
239 if [ -n "$LOG_DATEFORMAT" ] ; then
240 echo "Converting $lf"
241 cat "$lf" | python "$tmpdir/.ast_tsconvert.py" --format="$LOG_DATEFORMAT" --timezone="$LOG_TIMEZONE" > "${destfile}"
242 else
243 echo "Copying $lf"
244 cp "$lf" "${destfile}"
245 fi
246 done
247
248 echo "Creating /tmp/$tardir.tar.gz"
249 tar -czvf /tmp/$tardir.tar.gz -C $tmpdir $tardir 2>/dev/null
250
251 exit
252
253 # Be careful editing the inline scripts.
254 # They're space-indented.
255
256 # We need the python bit because lock_infos isn't
257 # a valid symbol in asterisk unless DEBUG_THREADS was
258 # used during the compile. Also, interrupt and continue
259 # are only valid for a running program.
260
261 #@@@SCRIPTSTART@@@
262 import argparse
263 import datetime as dt
264 import dateutil.tz as tz
265 import re
266 import sys
267 import time
268
269 parser = argparse.ArgumentParser(description="Make POSIX timestamps readable")
270 parser.add_argument('--format', action='store', required=True)
271 parser.add_argument('--timezone', action='store', required=False)
272 args=parser.parse_args()
273
274 # We only convert timestamps that are at the beginning of a line
275 # or are preceeded by a whitespace character or a '['
276 rets = re.compile(r'(^|(?<=\s|\[))\d+(\.\d+)?', flags=re.M)
277 if args.timezone and len(args.timezone) > 0:
278 tzf = tz.tzfile('/usr/share/zoneinfo/' + args.timezone)
279 else:
280 tzf = tz.tzfile('/etc/localtime')
281
282 now = time.time()
283 a_year_ago = now - (86400.0 * 365)
284
285 def convert(match):
286 ts = float(match.group(0))
287 if ts <= now and ts > a_year_ago and len(args.format) > 0:
288 return dt.datetime.fromtimestamp(ts, tzf).strftime(args.format)
289 else:
290 return match.group(0)
291
292 while 1:
293 line = sys.stdin.readline()
294 if not line:
295 break
296 print(rets.sub(convert, line))