| 1 |
# NOTE: we intentionally don't rely on shebang here, and expect this script to |
| 2 |
# be invoked as "bash nerdlog_agent.sh" explicitly, since it's likely the most |
| 3 |
# portable way (short of using /bin/sh, but that would be a bigger effort since |
| 4 |
# this script does rely on bash). |
| 5 |
|
| 6 |
# NOTE: ABANDON ALL HOPE. |
| 7 |
# |
| 8 |
# This script logic is really convoluted and hard to understand, and begs for a |
| 9 |
# major rewrite. |
| 10 |
|
| 11 |
trap 'echo "exit_code:$?"' EXIT |
| 12 |
|
| 13 |
# Arguments: |
| 14 |
# |
| 15 |
# --from, --to: time in the format "2006-01-02-15:04". |
| 16 |
|
| 17 |
# Those numbers are supposed to go up as the query progresses; the Go app |
| 18 |
# will then be able to tell which node is the slowest and show info for it. |
| 19 |
STAGE_INDEX_FULL=1 |
| 20 |
STAGE_INDEX_APPEND=2 |
| 21 |
STAGE_QUERYING=3 |
| 22 |
STAGE_DONE=4 |
| 23 |
|
| 24 |
SPECIAL_FILENAME_AUTO="auto" |
| 25 |
SPECIAL_FILENAME_JOURNALCTL="journalctl" |
| 26 |
|
| 27 |
# The output looks like this: |
| 28 |
# 2025-04-27T21:31:11.670468+00:00 myhot systemd[1]: Something happened. |
| 29 |
JOURNALCTL_FORMAT_FLAG="--output=short-iso-precise" |
| 30 |
|
| 31 |
indexfile=/tmp/nerdlog_agent_index |
| 32 |
|
| 33 |
logfile_prev="${SPECIAL_FILENAME_AUTO}" |
| 34 |
logfile_last="${SPECIAL_FILENAME_AUTO}" |
| 35 |
|
| 36 |
positional_args=() |
| 37 |
|
| 38 |
max_num_lines=100 |
| 39 |
|
| 40 |
awktime_month='monthByName[substr($0, 1, 3)]' |
| 41 |
awktime_year='yearByMonth[month]' |
| 42 |
awktime_day='(substr($0, 5, 1) == " ") ? "0" substr($0, 6, 1) : substr($0, 5, 2)' |
| 43 |
awktime_hhmm='substr($0, 8, 5)' |
| 44 |
awktime_minute_key='substr($0, 1, 12)' |
| 45 |
# TODO: double check that if any of these is provided manually in a flag, |
| 46 |
# then all of them are provided manually. |
| 47 |
|
| 48 |
function find_gawk_binary() { # {{{ |
| 49 |
gawk_path="$(which gawk)" |
| 50 |
if [[ $? == 0 ]]; then |
| 51 |
if [ -x "$gawk_path" ]; then |
| 52 |
awk_version_str="$($gawk_path --version)" |
| 53 |
if [[ $? == 0 ]]; then |
| 54 |
if echo "$awk_version_str" | grep -q 'GNU Awk'; then |
| 55 |
# gawk works fine |
| 56 |
echo "$gawk_path" |
| 57 |
exit 0 |
| 58 |
fi |
| 59 |
fi |
| 60 |
fi |
| 61 |
fi |
| 62 |
|
| 63 |
awk_path="$(which awk)" |
| 64 |
if [[ $? == 0 ]]; then |
| 65 |
if [ -x "$awk_path" ]; then |
| 66 |
awk_version_str="$($awk_path --version)" |
| 67 |
if [[ $? == 0 ]]; then |
| 68 |
if echo "$awk_version_str" | grep -q 'GNU Awk'; then |
| 69 |
# awk works fine |
| 70 |
echo "$awk_path" |
| 71 |
exit 0 |
| 72 |
fi |
| 73 |
fi |
| 74 |
fi |
| 75 |
fi |
| 76 |
|
| 77 |
exit 1 |
| 78 |
} # }}} |
| 79 |
|
| 80 |
function detect_timezone() { # {{{ |
| 81 |
# Prefer TZ env var if available |
| 82 |
if [[ "$TZ" != "" ]]; then |
| 83 |
echo "$TZ" |
| 84 |
exit 0 |
| 85 |
fi |
| 86 |
|
| 87 |
# Next check timedatectl if available |
| 88 |
host_timezone="$(timedatectl show --property=Timezone --value)" |
| 89 |
if [[ $? == 0 ]]; then |
| 90 |
echo "$host_timezone" |
| 91 |
exit 0 |
| 92 |
fi |
| 93 |
|
| 94 |
# Resort to /etc/timezone |
| 95 |
if [ -r /etc/timezone ]; then |
| 96 |
host_timezone="$(cat /etc/timezone)" |
| 97 |
if [[ $? == 0 ]]; then |
| 98 |
echo "$host_timezone" |
| 99 |
exit 0 |
| 100 |
fi |
| 101 |
fi |
| 102 |
|
| 103 |
# Then resort to browsing zoneinfo files manually |
| 104 |
zone_file="$(find /usr/share/zoneinfo -type f -exec cmp -s /etc/localtime '{}' \; -print)" |
| 105 |
if [[ $? == 0 ]]; then |
| 106 |
host_timezone="$(echo "$zone_file" | sed -e 's|^/usr/share/zoneinfo/||' -e '/posix/d')" |
| 107 |
if [[ $? == 0 ]]; then |
| 108 |
echo "$host_timezone" |
| 109 |
exit 0 |
| 110 |
fi |
| 111 |
fi |
| 112 |
|
| 113 |
exit 1 |
| 114 |
} # }}} |
| 115 |
|
| 116 |
# function concat_cmds_array() {{{ |
| 117 |
# |
| 118 |
# Concatenates the global `cmds` array into a single bash command, using " && ". |
| 119 |
# Escapes things properly. The result can be passed to "eval" or "bash -c". |
| 120 |
function concat_cmds_array() { |
| 121 |
local first=1 |
| 122 |
for cmd in "${cmds[@]}"; do |
| 123 |
if [[ $first == 1 ]]; then |
| 124 |
first=0 |
| 125 |
else |
| 126 |
echo -n " && " |
| 127 |
fi |
| 128 |
echo -n "${cmd//\'/\'\"\'\"\'}" |
| 129 |
done |
| 130 |
} # }}} |
| 131 |
|
| 132 |
while [[ $# -gt 0 ]]; do |
| 133 |
case $1 in |
| 134 |
-c|--index-file) |
| 135 |
indexfile="$2" |
| 136 |
shift # past argument |
| 137 |
shift # past value |
| 138 |
;; |
| 139 |
--logfile-last) |
| 140 |
logfile_last="$2" |
| 141 |
shift # past argument |
| 142 |
shift # past value |
| 143 |
;; |
| 144 |
--logfile-prev) |
| 145 |
logfile_prev="$2" |
| 146 |
shift # past argument |
| 147 |
shift # past value |
| 148 |
;; |
| 149 |
-f|--from) |
| 150 |
from="$2" |
| 151 |
shift # past argument |
| 152 |
shift # past value |
| 153 |
;; |
| 154 |
-t|--to) |
| 155 |
to="$2" |
| 156 |
shift # past argument |
| 157 |
shift # past value |
| 158 |
;; |
| 159 |
-u|--lines-until) |
| 160 |
lines_until="$2" |
| 161 |
shift # past argument |
| 162 |
shift # past value |
| 163 |
;; |
| 164 |
|
| 165 |
# The 3 arguments below: |
| 166 |
# --timestamp-until-seconds, --timestamp-until-precise, --skip-n-latest |
| 167 |
# are needed specifically for pagination in journalctl. |
| 168 |
# |
| 169 |
# It's all very ugly, but works correctly, and so far I'm not able to come |
| 170 |
# up with better alternatives (see below why --cursor etc isn't helpful for us). |
| 171 |
# |
| 172 |
# Let me explain what they mean exactly. Let's consider that we have the following |
| 173 |
# logs, some of which we already have loaded, and now we need to get the next page: |
| 174 |
# |
| 175 |
# ........ |
| 176 |
# 2025-03-10T11:49:44.123456+00:00 myhost myapp[123]: NEXT PAGE message |
| 177 |
# 2025-03-10T11:49:44.838785+00:00 myhost myapp[123]: NEXT PAGE message |
| 178 |
# 2025-03-10T11:49:44.838785+00:00 myhost myapp[123]: LOADED message |
| 179 |
# 2025-03-10T11:49:44.838785+00:00 myhost myapp[123]: LOADED message |
| 180 |
# 2025-03-10T11:49:44.988548+00:00 myhost myapp[123]: LOADED message |
| 181 |
# 2025-03-10T11:49:44.988548+00:00 myhost myapp[123]: LOADED message |
| 182 |
# 2025-03-10T11:49:44.999000+00:00 myhost myapp[123]: LOADED message |
| 183 |
# 2025-03-10T11:49:44.999000+00:00 myhost myapp[123]: LOADED message |
| 184 |
# 2025-03-10T11:49:45.002143+00:00 myhost myapp[123]: LOADED message |
| 185 |
# |
| 186 |
# So we already have two messages at the "2025-03-10T11:49:44.838785" |
| 187 |
# timestamp, and the next page should start from the remaining one message |
| 188 |
# on the same timestamp. |
| 189 |
# |
| 190 |
# So first, even though we technically can pass the --until '2025-03-10 11:49:44.838785 |
| 191 |
# argument to journalctl, which takes it without errors, it doesn't work |
| 192 |
# reliably: apparently the time indexing journalctl is doing does not have |
| 193 |
# microsecond precision, and it will actually stop EARLIER than the given |
| 194 |
# timestamp, missing arbitrary number of messages. |
| 195 |
# |
| 196 |
# To make sure that we do get all the messages we need, we have to request |
| 197 |
# a bit more, and round the --until timestamp to the next whole second: |
| 198 |
# '2025-03-10 11:49:45'. This is precisely what needs to be passed as the |
| 199 |
# --timestamp-until-seconds flag. |
| 200 |
# |
| 201 |
# And having that, we also need to know how many latest messages to filter |
| 202 |
# out, because we already have them. There are a few ways of doing it, but |
| 203 |
# currently implemented as follows: |
| 204 |
# |
| 205 |
# 1) --timestamp-until-precise is the exact timestamp of the very latest |
| 206 |
# message we have, formatted the way journalctl formats it, i.e. |
| 207 |
# '2025-03-10T11:49:44.838785' |
| 208 |
# 2) --skip-n-latest is how many messages we already have on this timestamp, |
| 209 |
# i.e. '2' in this case. |
| 210 |
# |
| 211 |
# Having that, the agent script knows everything it needs to know, and the |
| 212 |
# logic is as follows (btw don't forget that we call journalctl with the |
| 213 |
# --reverse, so we first get the latest messages, which we need to skip): |
| 214 |
# |
| 215 |
# - Check if the current timestamp from journalctl string is |
| 216 |
# lexicographically larger than the given --timestamp-until-precise. If |
| 217 |
# so, just skip it: we're only receiving this line because our |
| 218 |
# --timestamp-until-seconds was rounded up to the whole second |
| 219 |
# - Check if the current timestamp from journalctl string is exactly the |
| 220 |
# same as the given --timestamp-until-precise. If so, skip up to the |
| 221 |
# --skip-n-latest of such messages. |
| 222 |
# - Otherwise, we're good to include this message in the output. |
| 223 |
# |
| 224 |
# Now, why the journalctl built-in pagination mechanism (the --cursor and |
| 225 |
# related flags) doesn't work. Two primary reasons: |
| 226 |
# |
| 227 |
# - Journalctl only allows us to see the cursor of the *latest* message in |
| 228 |
# the output; |
| 229 |
# - We apply our filters, and limit number of lines, *after* journalctl, |
| 230 |
# using the awk script. |
| 231 |
# |
| 232 |
# So, there's no reliable way to say "print the latest N messages maching |
| 233 |
# this awk pattern, and show me the cursor of the first one, so that I can |
| 234 |
# later get next page". |
| 235 |
# |
| 236 |
# If there was a way to show the cursor for every single line that |
| 237 |
# journalctl outputs, then it might be possible, but then it would likely |
| 238 |
# make things even slower. |
| 239 |
# |
| 240 |
# So for now, we just have to hack around with the timestamps. Ugly, but |
| 241 |
# works, and covered with tests. |
| 242 |
|
| 243 |
--timestamp-until-seconds) |
| 244 |
timestamp_until_seconds="$2" |
| 245 |
shift # past argument |
| 246 |
shift # past value |
| 247 |
;; |
| 248 |
--timestamp-until-precise) |
| 249 |
timestamp_until_precise="$2" |
| 250 |
if [[ "$skip_n_latest" == "" ]]; then |
| 251 |
skip_n_latest=1 |
| 252 |
fi |
| 253 |
shift # past argument |
| 254 |
shift # past value |
| 255 |
;; |
| 256 |
--skip-n-latest) |
| 257 |
skip_n_latest="$2" |
| 258 |
shift # past argument |
| 259 |
shift # past value |
| 260 |
;; |
| 261 |
|
| 262 |
--refresh-index) |
| 263 |
refresh_index="1" |
| 264 |
shift # past argument |
| 265 |
;; |
| 266 |
-l|--max-num-lines) |
| 267 |
max_num_lines="$2" |
| 268 |
shift # past argument |
| 269 |
shift # past value |
| 270 |
;; |
| 271 |
|
| 272 |
--awktime-month) |
| 273 |
awktime_month="$2" |
| 274 |
shift # past argument |
| 275 |
shift # past value |
| 276 |
;; |
| 277 |
--awktime-year) |
| 278 |
awktime_year="$2" |
| 279 |
shift # past argument |
| 280 |
shift # past value |
| 281 |
;; |
| 282 |
--awktime-day) |
| 283 |
awktime_day="$2" |
| 284 |
shift # past argument |
| 285 |
shift # past value |
| 286 |
;; |
| 287 |
--awktime-hhmm) |
| 288 |
awktime_hhmm="$2" |
| 289 |
shift # past argument |
| 290 |
shift # past value |
| 291 |
;; |
| 292 |
--awktime-minute-key) |
| 293 |
awktime_minute_key="$2" |
| 294 |
shift # past argument |
| 295 |
shift # past value |
| 296 |
;; |
| 297 |
|
| 298 |
-*|--*) |
| 299 |
echo "Unknown option $1" 1>&2 |
| 300 |
exit 1 |
| 301 |
;; |
| 302 |
*) |
| 303 |
positional_args+=("$1") # save positional arg |
| 304 |
shift # past argument |
| 305 |
;; |
| 306 |
esac |
| 307 |
done |
| 308 |
|
| 309 |
set -- "${positional_args[@]}" # restore positional parameters |
| 310 |
|
| 311 |
if [[ $timestamp_until_precise != "" || $timestamp_until_seconds != "" || $skip_n_latest != "" ]]; then |
| 312 |
if [[ "$timestamp_until_precise" == "" ]]; then |
| 313 |
echo "error:--timestamp-until-seconds, --timestamp-until-precise, --skip-n-latest should all be given together, but --timestamp-until-precise is not set" 1>&2 |
| 314 |
exit 1 |
| 315 |
fi |
| 316 |
|
| 317 |
if [[ "$timestamp_until_seconds" == "" ]]; then |
| 318 |
echo "error:--timestamp-until-seconds, --timestamp-until-precise, --skip-n-latest should all be given together, but --timestamp-until-seconds is not set" 1>&2 |
| 319 |
exit 1 |
| 320 |
fi |
| 321 |
|
| 322 |
if [[ "$skip_n_latest" == "" ]]; then |
| 323 |
echo "error:--timestamp-until-seconds, --timestamp-until-precise, --skip-n-latest should all be given together, but --skip-n-latest is not set" 1>&2 |
| 324 |
exit 1 |
| 325 |
fi |
| 326 |
fi |
| 327 |
|
| 328 |
# Either use the provided current year and month (for tests), or get the actual ones. |
| 329 |
if [[ "$CUR_YEAR" == "" ]]; then |
| 330 |
CUR_YEAR="$(date +'%Y')" |
| 331 |
fi |
| 332 |
|
| 333 |
if [[ "$CUR_MONTH" == "" ]]; then |
| 334 |
CUR_MONTH="$(date +'%m')" |
| 335 |
fi |
| 336 |
|
| 337 |
# TODO: instead of always detecting it, add support for the --awk-binary flag, |
| 338 |
# and only autodetect if it wasn't provided. Also, gotta always do this during |
| 339 |
# logstream_info command. |
| 340 |
awk_binary="$(find_gawk_binary)" |
| 341 |
if [[ $? != 0 ]]; then |
| 342 |
echo "error:gawk (GNU Awk) is a requirement, but not found on the system. Please install it, then retry" 1>&2 |
| 343 |
exit 1 |
| 344 |
fi |
| 345 |
|
| 346 |
# Use either a real journalctl, or a mocked one. |
| 347 |
journalctl_binary="journalctl" |
| 348 |
if [[ "${NERDLOG_JOURNALCTL_MOCK}" != "" ]]; then |
| 349 |
journalctl_binary="${NERDLOG_JOURNALCTL_MOCK}" |
| 350 |
fi |
| 351 |
|
| 352 |
os_kind="" |
| 353 |
case "$(uname -s)" in |
| 354 |
Linux) |
| 355 |
os_kind="linux" |
| 356 |
;; |
| 357 |
Darwin) |
| 358 |
os_kind="macos" |
| 359 |
;; |
| 360 |
FreeBSD|OpenBSD|NetBSD|DragonFly) |
| 361 |
os_kind="bsd" |
| 362 |
;; |
| 363 |
*) |
| 364 |
echo "error:unknown kernel name $(uname -s)" 2>&1 |
| 365 |
exit 1 |
| 366 |
esac |
| 367 |
|
| 368 |
# TODO: also check that gawk is recent enough; the -b option that we need |
| 369 |
# was introduced in 4.0.0, released in 2011: |
| 370 |
# https://lists.gnu.org/archive/html/info-gnu/2011-06/msg00013.html |
| 371 |
# Since it's so old, not bothering to check the version for now. |
| 372 |
|
| 373 |
if [[ "$logfile_last" == "${SPECIAL_FILENAME_AUTO}" ]]; then |
| 374 |
if [ -e /var/log/messages ]; then |
| 375 |
logfile_last=/var/log/messages |
| 376 |
elif [ -e /var/log/syslog ]; then |
| 377 |
logfile_last=/var/log/syslog |
| 378 |
elif command -v journalctl > /dev/null 2>&1; then |
| 379 |
logfile_last="${SPECIAL_FILENAME_JOURNALCTL}" |
| 380 |
else |
| 381 |
echo "error:failed to autodetect log file: neither /var/log/messages nor /var/log/syslog log files are present, and journalctl is not available either. Specify the log file manually" 1>&2 |
| 382 |
exit 1 |
| 383 |
fi |
| 384 |
fi |
| 385 |
|
| 386 |
if [[ "$logfile_prev" == "${SPECIAL_FILENAME_AUTO}" ]]; then |
| 387 |
if [[ "$logfile_last" != "${SPECIAL_FILENAME_JOURNALCTL}" ]]; then |
| 388 |
# For now just blindly append ".1" to the first logfile; if it doesn't actually |
| 389 |
# exist, we'll handle this case right below. |
| 390 |
logfile_prev="${logfile_last}.1" |
| 391 |
else |
| 392 |
# Set it to the same special value |
| 393 |
logfile_prev="${SPECIAL_FILENAME_JOURNALCTL}" |
| 394 |
fi |
| 395 |
fi |
| 396 |
|
| 397 |
# A simple hack to account for cases when /var/log/syslog.1 doesn't exist: |
| 398 |
# create an empty file and pretend that it's an empty log file. |
| 399 |
if [ ! -e "$logfile_prev" ] && [[ "$logfile_prev" != "${SPECIAL_FILENAME_JOURNALCTL}" ]]; then |
| 400 |
echo "debug:prev logfile $logfile_prev doesn't exist, using a dummy empty file /tmp/nerdlog-empty-file" 1>&2 |
| 401 |
# TODO: instead of using the same file /tmp/nerdlog-empty-file , maybe |
| 402 |
# generate the name based on the index filename, to make the tests more |
| 403 |
# self-contained. |
| 404 |
logfile_prev="/tmp/nerdlog-empty-file" |
| 405 |
if [ ! -f "$logfile_prev" ] || [ -s "$logfile_prev" ]; then |
| 406 |
rm -f $logfile_prev || exit 1 |
| 407 |
touch $logfile_prev || exit 1 |
| 408 |
fi |
| 409 |
|
| 410 |
# For stable output in tests, also update the creation/modification time of |
| 411 |
# that file to be the same as the first log file. It's not portable though |
| 412 |
# (not gonna work on BSD), but it's non-essential functionality, so we just |
| 413 |
# ignore any errors here and do nothing then. |
| 414 |
ctime=$(stat -c %W $logfile_last 2>/dev/null) |
| 415 |
if [[ $? == 0 ]]; then |
| 416 |
touch -d "@$ctime" $logfile_prev |
| 417 |
fi |
| 418 |
fi |
| 419 |
|
| 420 |
command="$1" |
| 421 |
if [[ "${command}" == "" ]]; then |
| 422 |
echo "error:command is required" 1>&2 |
| 423 |
exit 1 |
| 424 |
fi |
| 425 |
|
| 426 |
case "${command}" in |
| 427 |
query) |
| 428 |
shift |
| 429 |
# Will be handled below. |
| 430 |
;; |
| 431 |
|
| 432 |
logstream_info) |
| 433 |
host_timezone="$(detect_timezone)" |
| 434 |
if [[ $? == 0 ]]; then |
| 435 |
echo "host_timezone:$host_timezone" |
| 436 |
else |
| 437 |
echo "warn:failed to detect host timezone" |
| 438 |
fi |
| 439 |
|
| 440 |
if [[ "${logfile_last}" != "${SPECIAL_FILENAME_JOURNALCTL}" ]]; then |
| 441 |
if [ ! -e ${logfile_last} ]; then |
| 442 |
echo "error:${logfile_last} does not exist" 1>&2 |
| 443 |
exit 1 |
| 444 |
fi |
| 445 |
|
| 446 |
if [ ! -r ${logfile_last} ]; then |
| 447 |
echo "error:${logfile_last} exists but is not readable, check your permissions" 1>&2 |
| 448 |
exit 1 |
| 449 |
fi |
| 450 |
|
| 451 |
if [ ! -e ${logfile_prev} ]; then |
| 452 |
echo "error:${logfile_prev} does not exist" 1>&2 |
| 453 |
exit 1 |
| 454 |
fi |
| 455 |
|
| 456 |
if [ ! -r ${logfile_prev} ]; then |
| 457 |
echo "error:${logfile_prev} exists but is not readable, check your permissions" 1>&2 |
| 458 |
exit 1 |
| 459 |
fi |
| 460 |
|
| 461 |
# Print a bunch of example log lines, so that the client can autodetect the |
| 462 |
# format. |
| 463 |
if [ -s ${logfile_last} ]; then |
| 464 |
last_line="$(tail -n 1 ${logfile_last})" || exit 1 |
| 465 |
first_line="$(head -n 1 ${logfile_last})" || exit 1 |
| 466 |
echo "example_log_line:$last_line" |
| 467 |
echo "example_log_line:$first_line" |
| 468 |
fi |
| 469 |
if [ -s ${logfile_prev} ]; then |
| 470 |
last_line="$(tail -n 1 ${logfile_prev})" || exit 1 |
| 471 |
first_line="$(head -n 1 ${logfile_prev})" || exit 1 |
| 472 |
echo "example_log_line:$last_line" |
| 473 |
echo "example_log_line:$first_line" |
| 474 |
fi |
| 475 |
else |
| 476 |
# We need to use journalctl, check if it's executable |
| 477 |
if ! command -v "$journalctl_binary" > /dev/null 2>&1; then |
| 478 |
echo "error:journalctl is not found" 1>&2 |
| 479 |
exit 1 |
| 480 |
fi |
| 481 |
|
| 482 |
# Check if the user has access to all system logs (as opposed to only its |
| 483 |
# own logs). Ideally we'd ask journalctl, but it doesn't seem to provide |
| 484 |
# a way to learn this easily, so for now just checking user id and groups |
| 485 |
# manually. |
| 486 |
if ! [[ "$(id -u)" == 0 || " $(id -Gn) " == *" adm "* || " $(id -Gn) " == *" systemd-journal "* ]]; then |
| 487 |
# User is not root, and is not in the adm or systemd-journal groups. |
| 488 |
# Print a warning so that the client script can show it on the UI somehow. |
| 489 |
echo "warn_journalctl_no_admin_access" 1>&2 |
| 490 |
fi |
| 491 |
|
| 492 |
# And print one line for the timestamp format autodetection. |
| 493 |
last_line="$($journalctl_binary $JOURNALCTL_FORMAT_FLAG --quiet -n 1)" || exit 1 |
| 494 |
echo "example_log_line:$last_line" |
| 495 |
fi |
| 496 |
|
| 497 |
exit 0 |
| 498 |
;; |
| 499 |
|
| 500 |
*) |
| 501 |
echo "error:invalid command ${command}" 1>&2 |
| 502 |
exit 1 |
| 503 |
esac |
| 504 |
|
| 505 |
# What follows is the handler for the "query" command. |
| 506 |
|
| 507 |
# NOTE: we only show percentages with 5% increments, to save on traffic and |
| 508 |
# other overhead. With all 24 my-nodes, having percentage being printed with |
| 509 |
# 1% increments, it generates extra traffic of about 290KB per single query, |
| 510 |
# wow. With 5% increments, the overhead is about 70 KB. |
| 511 |
awk_func_print_percentage=' |
| 512 |
function printPercentage(numCur, numTotal) { |
| 513 |
curPercent = int(numCur/numTotal*20); |
| 514 |
if (curPercent != lastPercent) { |
| 515 |
print "p:p:" curPercent*5 >> "/dev/stderr" |
| 516 |
lastPercent = curPercent |
| 517 |
} |
| 518 |
} |
| 519 |
' |
| 520 |
|
| 521 |
function run_awk_script_logfiles { |
| 522 |
awk_pattern='' |
| 523 |
if [[ "$user_pattern" != "" ]]; then |
| 524 |
awk_pattern="!($user_pattern) {numFilteredOut++; next}" |
| 525 |
fi |
| 526 |
|
| 527 |
# NOTE: this script MUST be executed with the "-b" awk key, which means that |
| 528 |
# awk will work in terms of bytes, not characters. We use length($0) there and |
| 529 |
# we rely on it being number of bytes. |
| 530 |
# |
| 531 |
# Also btw, percentage calculation slows the whole query by about 10%, which |
| 532 |
# isn't ideal. TODO: maybe instead of doing the division on every line, we can |
| 533 |
# only do the division when the percentage changes, so we calculate the next |
| 534 |
# point when it'd change, and going forward we just compare it with a simple |
| 535 |
# "<". |
| 536 |
awk_script=' |
| 537 |
'$awk_func_print_percentage' |
| 538 |
|
| 539 |
BEGIN { |
| 540 |
bytenr=1; curline=0; maxlines='$max_num_lines'; lastPercent=0; |
| 541 |
numFilteredOut=0; |
| 542 |
prevMinKey=""; |
| 543 |
} |
| 544 |
{ bytenr += length($0)+1 } |
| 545 |
NR % 100 == 0 { |
| 546 |
printPercentage(bytenr, '$num_bytes_to_scan') |
| 547 |
} |
| 548 |
'$awk_pattern' |
| 549 |
{ |
| 550 |
curMinKey = '"$awktime_minute_key"'; |
| 551 |
|
| 552 |
# NOTE: this was a naive attempt to better handle the case when timestamps |
| 553 |
# have decreased: instead of incrementing the bucket of the decreased |
| 554 |
# timestamp, we ideally want to increment the bucket of the last |
| 555 |
# non-decreased timestamp. |
| 556 |
# |
| 557 |
# However, to make it work properly, the minute key needs to be formatted |
| 558 |
# so that a later timestamp is always lexocographically larger than an |
| 559 |
# earlier timestamp, and while it is possible to implement it this way, |
| 560 |
# it slows things down significantly, which seems unjustified just to |
| 561 |
# handle this corner case more gracefully. |
| 562 |
# |
| 563 |
# We might still implement it at some point and make it optional, but for |
| 564 |
# now, keeping things simple and just not caring about this corner case. |
| 565 |
# |
| 566 |
## Account for decreased timestamps. |
| 567 |
## |
| 568 |
## NOTE: to make it produce the correct result in all cases, this check |
| 569 |
## needs to be before the pattern check, but we intentionally avoid doing |
| 570 |
## that because it slows things down by 5-10% when the pattern filters out |
| 571 |
## most of the lines, which I think is not worth it to account for this |
| 572 |
## corner case. |
| 573 |
#if (curMinKey < prevMinKey) { |
| 574 |
#curMinKey = prevMinKey; |
| 575 |
#} else { |
| 576 |
#prevMinKey = curMinKey; |
| 577 |
#} |
| 578 |
|
| 579 |
stats[curMinKey]++; |
| 580 |
|
| 581 |
'$lines_until_check' |
| 582 |
|
| 583 |
lastlines[curline] = $0; |
| 584 |
lastNRs[curline] = NR; |
| 585 |
curline++ |
| 586 |
if (curline >= maxlines) { |
| 587 |
curline = 0; |
| 588 |
} |
| 589 |
|
| 590 |
next; |
| 591 |
} |
| 592 |
|
| 593 |
END { |
| 594 |
print "debug:Filtered out " numFilteredOut " from " NR " lines" > "/dev/stderr" |
| 595 |
|
| 596 |
print "logfile:'$logfile_prev':0"; |
| 597 |
print "logfile:'$logfile_last':'$prevlog_lines'"; |
| 598 |
|
| 599 |
for (x in stats) { |
| 600 |
print "s:" x "," stats[x] |
| 601 |
} |
| 602 |
|
| 603 |
for (i = 0; i < maxlines; i++) { |
| 604 |
ln = curline + i; |
| 605 |
if (ln >= maxlines) { |
| 606 |
ln -= maxlines; |
| 607 |
} |
| 608 |
|
| 609 |
if (!lastlines[ln]) { |
| 610 |
continue; |
| 611 |
} |
| 612 |
|
| 613 |
curNR = lastNRs[ln] + '$from_linenr_int' - 1; |
| 614 |
|
| 615 |
print "m:" curNR ":" lastlines[ln]; |
| 616 |
} |
| 617 |
} |
| 618 |
' |
| 619 |
|
| 620 |
"$awk_binary" -b "$awk_script" "$@" |
| 621 |
if [[ "$?" != 0 ]]; then |
| 622 |
return 1 |
| 623 |
fi |
| 624 |
} |
| 625 |
|
| 626 |
function run_awk_script_journalctl { |
| 627 |
awk_pattern_check='' |
| 628 |
if [[ "$user_pattern" != "" ]]; then |
| 629 |
awk_pattern_check="!($user_pattern) {numFilteredOut++; next}" |
| 630 |
fi |
| 631 |
|
| 632 |
awk_skip_n_latest_check='' |
| 633 |
if [[ "$timestamp_until_precise" != "" && "$skip_n_latest" != "" ]]; then |
| 634 |
awk_skip_n_latest_check=' |
| 635 |
(needToSkip) { |
| 636 |
curtime = substr($0, 1, timestampUntilPreciseLen); |
| 637 |
|
| 638 |
# If the timestamp is larger than what we already have, just skip. |
| 639 |
if (curtime > timestampUntilPrecise) { |
| 640 |
next; |
| 641 |
} |
| 642 |
|
| 643 |
# If the timestamp is exactly the same as what we already have, |
| 644 |
# skip the skip_n_latest lines. |
| 645 |
if (curtime == timestampUntilPrecise) { |
| 646 |
numSameTimestamp++; |
| 647 |
if (numSameTimestamp <= '"$skip_n_latest"') { |
| 648 |
next; |
| 649 |
} |
| 650 |
|
| 651 |
# We have skipped enough lines, remember that |
| 652 |
print "debug:Skipped " NR-1 " latest lines" > "/dev/stderr" |
| 653 |
needToSkip = 0; |
| 654 |
} |
| 655 |
|
| 656 |
# If the timestamp is earlier than what we already have, |
| 657 |
# remember that we are done skipping, to avoid doing useless work. |
| 658 |
if (curtime < timestampUntilPrecise) { |
| 659 |
print "debug:Skipped " NR-1 " latest lines" > "/dev/stderr" |
| 660 |
needToSkip = 0; |
| 661 |
} |
| 662 |
} |
| 663 |
' |
| 664 |
fi |
| 665 |
|
| 666 |
early_exit_check='' |
| 667 |
if [[ "$stop_after_max_num_lines" != "" ]]; then |
| 668 |
early_exit_check='curline >= maxlines { |
| 669 |
print "debug:Exiting early after collecting " curline " lines" > "/dev/stderr" |
| 670 |
exit |
| 671 |
}' |
| 672 |
fi |
| 673 |
|
| 674 |
awk_script=' |
| 675 |
'$awk_func_print_percentage' |
| 676 |
|
| 677 |
# Takes timestamp in the same format as we use for --from and --to and |
| 678 |
# store in the index ("2006-01-02-15:04"), and returns the corresponding unix |
| 679 |
# timestamp. |
| 680 |
function indexTimestrToTimestamp(timestr) { |
| 681 |
year = substr(timestr, 1, 4); |
| 682 |
month = substr(timestr, 6, 2); |
| 683 |
day = substr(timestr, 9, 2); |
| 684 |
hh = substr(timestr, 12, 2); |
| 685 |
mm = substr(timestr, 15, 2); |
| 686 |
|
| 687 |
return mktime(year " " month " " day " " hh " " mm " 00"); |
| 688 |
} |
| 689 |
|
| 690 |
BEGIN { |
| 691 |
curline=0; |
| 692 |
lastline=""; |
| 693 |
maxlines='$max_num_lines'; |
| 694 |
numFilteredOut=0; |
| 695 |
lastPercent=-1; |
| 696 |
timestampUntilPrecise="'"$timestamp_until_precise"'"; |
| 697 |
timestampUntilPreciseLen=length(timestampUntilPrecise); |
| 698 |
numSameTimestamp=0; |
| 699 |
needToSkip = timestampUntilPreciseLen > 0 ? 1 : 0; |
| 700 |
|
| 701 |
# Find out earliest and latest timestamp for percentage calculations. |
| 702 |
earliestTimestamp=0; |
| 703 |
latestTimestamp=0; |
| 704 |
|
| 705 |
if ("'$from'" != "") { |
| 706 |
earliestTimestamp = indexTimestrToTimestamp("'$from'"); |
| 707 |
} else { |
| 708 |
# No "from" timestamp; technically it is possible to get it using |
| 709 |
# "journalctl --no-pager | head -n 1", but not bothering for now |
| 710 |
# because nerdlog always provides the --from. |
| 711 |
# |
| 712 |
# If it happens, the script will just not print any percentages |
| 713 |
# because timespanSeconds will be 0. |
| 714 |
} |
| 715 |
|
| 716 |
if ("'$to'" != "") { |
| 717 |
latestTimestamp = indexTimestrToTimestamp("'$to'"); |
| 718 |
} else { |
| 719 |
# No "to" timestamp; just use the current time. |
| 720 |
latestTimestamp = systime(); |
| 721 |
} |
| 722 |
|
| 723 |
timespanSeconds = 0; |
| 724 |
if (earliestTimestamp != 0 && latestTimestamp != 0) { |
| 725 |
timespanSeconds = latestTimestamp - earliestTimestamp; |
| 726 |
} |
| 727 |
} |
| 728 |
|
| 729 |
{ |
| 730 |
# Unfortunately journalctl prints multiline messages without the leading |
| 731 |
# timestamp and other details: instead, they just add padding with spaces, |
| 732 |
# which breaks our parsing; so we manually replace this padding with the |
| 733 |
# details from the previous non-padded line. |
| 734 |
if (substr($0, 1, 1) == " ") { |
| 735 |
# Find out the number of leading spaces |
| 736 |
numLeadingSpace = length($0) |
| 737 |
if (NF > 0) { |
| 738 |
numLeadingSpace = index($0, $1) - 1; |
| 739 |
} |
| 740 |
|
| 741 |
if (length(lastline) < numLeadingSpace) { |
| 742 |
print "error:line has more leading whitespaces than the length of the previous line"; |
| 743 |
exit 1; |
| 744 |
} |
| 745 |
|
| 746 |
# Replace these leading spaces with the same amount of characters from the previous line. |
| 747 |
$0 = substr(lastline, 1, numLeadingSpace) substr($0, numLeadingSpace + 1); |
| 748 |
} |
| 749 |
|
| 750 |
lastline = $0; |
| 751 |
} |
| 752 |
|
| 753 |
# Print percentage based on time. It is not as great as if it was |
| 754 |
# based on the number of bytes as we have it for the logfiles (because the |
| 755 |
# pace at which the percentage progresses will vary based on the intensivity |
| 756 |
# of the logs), but for journalctl we can hardly do any better. |
| 757 |
NR % 1000 == 0 { |
| 758 |
month = '"$awktime_month"'; |
| 759 |
year = '"$awktime_year"'; |
| 760 |
day = '"$awktime_day"'; |
| 761 |
hhmm = '"$awktime_hhmm"'; |
| 762 |
hh = substr(hhmm, 1, 2); |
| 763 |
mm = substr(hhmm, 4, 2); |
| 764 |
curTimestamp = mktime(year " " month " " day " " hh " " mm " 00"); |
| 765 |
|
| 766 |
if (timespanSeconds > 0) { |
| 767 |
printPercentage(latestTimestamp-curTimestamp, timespanSeconds) |
| 768 |
} else { |
| 769 |
# We do not know the timespan, so just do not print any percentages. |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
'$awk_pattern_check' |
| 774 |
'$awk_skip_n_latest_check' |
| 775 |
{ |
| 776 |
stats['"$awktime_minute_key"']++; |
| 777 |
|
| 778 |
if (curline < maxlines) { |
| 779 |
lines[curline] = $0; |
| 780 |
curline++ |
| 781 |
} |
| 782 |
} |
| 783 |
'$early_exit_check' |
| 784 |
|
| 785 |
END { |
| 786 |
print "debug:Filtered out " numFilteredOut " from " NR " lines" > "/dev/stderr" |
| 787 |
|
| 788 |
print "logfile:'$logfile_last':0"; |
| 789 |
|
| 790 |
for (x in stats) { |
| 791 |
print "s:" x "," stats[x] |
| 792 |
} |
| 793 |
|
| 794 |
for (i = curline-1; i >= 0; i--) { |
| 795 |
print "m:0:" lines[i]; |
| 796 |
} |
| 797 |
} |
| 798 |
' |
| 799 |
|
| 800 |
"$awk_binary" "$awk_script" "$@" |
| 801 |
if [[ "$?" != 0 ]]; then |
| 802 |
return 1 |
| 803 |
fi |
| 804 |
} |
| 805 |
|
| 806 |
user_pattern=$1 |
| 807 |
|
| 808 |
if [[ "$logfile_last" == "${SPECIAL_FILENAME_JOURNALCTL}" ]]; then |
| 809 |
echo "p:stage:$STAGE_QUERYING:querying logs:Note that journalctl can be SLOW. Consider using log files." 1>&2 |
| 810 |
|
| 811 |
# For both $from and $to, convert the format |
| 812 |
# "2006-01-02-15:04" -> "2006-01-02 15:04:00" |
| 813 |
journalctl_from="" |
| 814 |
if [[ "$from" != "" ]]; then |
| 815 |
journalctl_from="${from:0:10} ${from:11}:00" |
| 816 |
fi |
| 817 |
|
| 818 |
journalctl_to="" |
| 819 |
if [[ "$to" != "" ]]; then |
| 820 |
journalctl_to="${to:0:10} ${to:11}:00" |
| 821 |
fi |
| 822 |
|
| 823 |
stop_after_max_num_lines="" |
| 824 |
|
| 825 |
# Build journalctl command. |
| 826 |
# |
| 827 |
# --quiet is needed to suppress lines like "-- No entries --" or other |
| 828 |
# human-readable informative things; we only need logs since we parse them. |
| 829 |
# |
| 830 |
# --reverse is needed because it simplifies things and allows optimization in |
| 831 |
# some cases: in the awk script, we don't have to keep circular buffer for |
| 832 |
# all the lines and then print the last ones (like we do when reading log |
| 833 |
# files); and also when we're just getting the next page and not interested |
| 834 |
# in timeline histogram data for the full period, we just exit early after |
| 835 |
# accumulating $max_num_lines. |
| 836 |
cmd="$journalctl_binary $JOURNALCTL_FORMAT_FLAG --quiet --reverse" |
| 837 |
|
| 838 |
if [[ -n "$journalctl_from" ]]; then |
| 839 |
cmd="$cmd --since \"$journalctl_from\"" |
| 840 |
fi |
| 841 |
|
| 842 |
if [[ -n "$timestamp_until_seconds" ]]; then |
| 843 |
cmd="$cmd --until \"$timestamp_until_seconds\"" |
| 844 |
stop_after_max_num_lines="1" |
| 845 |
# NOTE: we'll also skip the $skip_n_latest messages with the latest timestamp. |
| 846 |
elif [[ -n "$journalctl_to" ]]; then |
| 847 |
cmd="$cmd --until \"$journalctl_to\"" |
| 848 |
fi |
| 849 |
|
| 850 |
echo "debug:Command to filter logs by time range:" 1>&2 |
| 851 |
echo "debug: $cmd" 1>&2 |
| 852 |
|
| 853 |
eval "${cmd}" | \ |
| 854 |
user_pattern="$user_pattern" \ |
| 855 |
max_num_lines="$max_num_lines" \ |
| 856 |
stop_after_max_num_lines="$stop_after_max_num_lines" \ |
| 857 |
timestamp_until_precise="$timestamp_until_precise" \ |
| 858 |
skip_n_latest="$skip_n_latest" \ |
| 859 |
run_awk_script_journalctl - |
| 860 |
|
| 861 |
codes=(${PIPESTATUS[@]}) |
| 862 |
for status in "${codes[@]}"; do |
| 863 |
# The exit code 141 means SIGPIPE + 128, which is what journalctl returns |
| 864 |
# if awk didn't consume the whole output, which is totally normal when |
| 865 |
# we're querying the next page and exiting after getting enough lines. |
| 866 |
if [[ $status -ne 0 && $status -ne 141 ]]; then |
| 867 |
exit 1 |
| 868 |
fi |
| 869 |
done |
| 870 |
|
| 871 |
echo "p:stage:$STAGE_DONE:done" 1>&2 |
| 872 |
|
| 873 |
exit 0 |
| 874 |
fi |
| 875 |
|
| 876 |
# A portable function to get file size. |
| 877 |
# Usage: get_file_size /path/to/file |
| 878 |
get_file_size() { |
| 879 |
case $os_kind in |
| 880 |
linux) |
| 881 |
stat -c %s "$1" |
| 882 |
;; |
| 883 |
macos|bsd) |
| 884 |
stat -f %z "$1" |
| 885 |
;; |
| 886 |
*) |
| 887 |
echo "error:internal error: invalid os_kind '$os_kind'" 1>&2 |
| 888 |
return 1 |
| 889 |
esac |
| 890 |
} |
| 891 |
|
| 892 |
# A portable function to get file modification time. |
| 893 |
# Usage: get_file_modtime /path/to/file |
| 894 |
get_file_modtime() { |
| 895 |
case $os_kind in |
| 896 |
linux) |
| 897 |
stat -c %y "$1" |
| 898 |
;; |
| 899 |
macos|bsd) |
| 900 |
# It's not exactly equivalent of the GNU version: it doesn't print |
| 901 |
# fractional seconds, but good enough for our needs. |
| 902 |
stat -f "%SB" -t "%Y-%m-%d %H:%M:%S" "$1" |
| 903 |
;; |
| 904 |
*) |
| 905 |
echo "error:internal error: invalid os_kind '$os_kind'" 1>&2 |
| 906 |
return 1 |
| 907 |
esac |
| 908 |
} |
| 909 |
|
| 910 |
logfile_prev_size=$(get_file_size $logfile_prev) || exit 1 |
| 911 |
logfile_last_size=$(get_file_size $logfile_last) || exit 1 |
| 912 |
total_size=$((logfile_prev_size+logfile_last_size)) || exit 1 |
| 913 |
|
| 914 |
if [[ "$refresh_index" == "1" ]]; then |
| 915 |
rm -f $indexfile || exit 1 |
| 916 |
fi |
| 917 |
|
| 918 |
function refresh_index { # {{{ |
| 919 |
local last_linenr=0 |
| 920 |
local last_bytenr=0 |
| 921 |
local prevlog_bytes=$(get_prevlog_bytenr) |
| 922 |
|
| 923 |
awk_vars=' |
| 924 |
monthByName["Jan"] = "01"; |
| 925 |
monthByName["Feb"] = "02"; |
| 926 |
monthByName["Mar"] = "03"; |
| 927 |
monthByName["Apr"] = "04"; |
| 928 |
monthByName["May"] = "05"; |
| 929 |
monthByName["Jun"] = "06"; |
| 930 |
monthByName["Jul"] = "07"; |
| 931 |
monthByName["Aug"] = "08"; |
| 932 |
monthByName["Sep"] = "09"; |
| 933 |
monthByName["Oct"] = "10"; |
| 934 |
monthByName["Nov"] = "11"; |
| 935 |
monthByName["Dec"] = "12"; |
| 936 |
|
| 937 |
curYear = '${CUR_YEAR}'; |
| 938 |
curMonth = '${CUR_MONTH}'; |
| 939 |
|
| 940 |
yearByMonth["01"] = inferYear(1, curYear, curMonth) ""; |
| 941 |
yearByMonth["02"] = inferYear(2, curYear, curMonth) ""; |
| 942 |
yearByMonth["03"] = inferYear(3, curYear, curMonth) ""; |
| 943 |
yearByMonth["04"] = inferYear(4, curYear, curMonth) ""; |
| 944 |
yearByMonth["05"] = inferYear(5, curYear, curMonth) ""; |
| 945 |
yearByMonth["06"] = inferYear(6, curYear, curMonth) ""; |
| 946 |
yearByMonth["07"] = inferYear(7, curYear, curMonth) ""; |
| 947 |
yearByMonth["08"] = inferYear(8, curYear, curMonth) ""; |
| 948 |
yearByMonth["09"] = inferYear(9, curYear, curMonth) ""; |
| 949 |
yearByMonth["10"] = inferYear(10, curYear, curMonth) ""; |
| 950 |
yearByMonth["11"] = inferYear(11, curYear, curMonth) ""; |
| 951 |
yearByMonth["12"] = inferYear(12, curYear, curMonth) ""; |
| 952 |
' |
| 953 |
|
| 954 |
# Add new entries to index, if needed |
| 955 |
|
| 956 |
# NOTE: syslogFieldsToIndexTimestr parses the traditional systemd timestamp |
| 957 |
# format, like this: "Apr 5 11:07:46". But in the recent versions of |
| 958 |
# rsyslog, it's not the default; that traditional timestamp format can be |
| 959 |
# enabled by adding this line: |
| 960 |
# |
| 961 |
# $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat |
| 962 |
# |
| 963 |
# to /etc/rsyslog.conf |
| 964 |
# |
| 965 |
# To use ISO 1806 instead (which is the default in recent rsyslog versions), |
| 966 |
# like "2025-04-05T11:07:46.161001+03:00": |
| 967 |
# |
| 968 |
# $ActionFileDefaultTemplate RSYSLOG_FileFormat |
| 969 |
# |
| 970 |
# But this function (and its usages) need to be updated to support it, and a |
| 971 |
# bunch of other time-filtering logic here. Although it's cool since it |
| 972 |
# includes the year, microseconds, and timezone. |
| 973 |
awk_functions=' |
| 974 |
function inferYear(logMonth, curYear, curMonth) { |
| 975 |
delta = logMonth - curMonth |
| 976 |
|
| 977 |
if (delta <= -11) # log month is Jan, current is Dec -> next year |
| 978 |
return curYear + 1 |
| 979 |
else if (delta >= 8) # log month is Sep-Dec, current is Jan -> previous year |
| 980 |
return curYear - 1 |
| 981 |
else |
| 982 |
return curYear |
| 983 |
} |
| 984 |
|
| 985 |
function printIndexLine(outfile, timestr, linenr, bytenr) { |
| 986 |
print "idx\t" timestr "\t" linenr "\t" bytenr >> outfile; |
| 987 |
} |
| 988 |
|
| 989 |
'$awk_func_print_percentage' |
| 990 |
' |
| 991 |
# NOTE: this script MUST be executed with the "-b" awk key, which means that |
| 992 |
# awk will work in terms of bytes, not characters. We use length($0) there and |
| 993 |
# we rely on it being number of bytes. |
| 994 |
|
| 995 |
scriptInitFromLastTimestr=' |
| 996 |
lastHHMM = substr(lastTimestr, 8, 5); |
| 997 |
' |
| 998 |
|
| 999 |
scriptSetCurTimestr=' |
| 1000 |
bytenr_cur = bytenr_next - length($0) - 1; |
| 1001 |
|
| 1002 |
month = '"$awktime_month"'; |
| 1003 |
year = '"$awktime_year"'; |
| 1004 |
day = '"$awktime_day"'; |
| 1005 |
hhmm = '"$awktime_hhmm"'; |
| 1006 |
|
| 1007 |
curTimestr = year "-" month "-" day "-" hhmm; |
| 1008 |
|
| 1009 |
# Ignore decreased timestamps: treat them as if the timestamp did not change. |
| 1010 |
if (curTimestr < lastTimestr) { |
| 1011 |
# TODO: make sure to print that once per occurrence, and uncomment. |
| 1012 |
# print "warn_timestamp_decreased:from " lastTimestr " to " curTimestr > "/dev/stderr" |
| 1013 |
next; |
| 1014 |
} |
| 1015 |
' |
| 1016 |
scriptSetLastTimestrEtc=' |
| 1017 |
lastTimestr = curTimestr; |
| 1018 |
lastHHMM = curHHMM; |
| 1019 |
' |
| 1020 |
|
| 1021 |
script1='BEGIN { bytenr_next=1; lastPercent=0 } |
| 1022 |
{ |
| 1023 |
bytenr_next += length($0)+1 |
| 1024 |
curHHMM = '"$awktime_hhmm"'; |
| 1025 |
}' |
| 1026 |
|
| 1027 |
if [ -s $indexfile ] |
| 1028 |
then |
| 1029 |
echo "p:stage:$STAGE_INDEX_APPEND:indexing up" 1>&2 |
| 1030 |
|
| 1031 |
local lastTimestr="$(tail -n 1 $indexfile | cut -f2)" |
| 1032 |
local last_linenr="$(tail -n 1 $indexfile | cut -f3)" |
| 1033 |
local last_bytenr="$(tail -n 1 $indexfile | cut -f4)" |
| 1034 |
local size_to_index=$((total_size-last_bytenr)) |
| 1035 |
|
| 1036 |
tail -c +$((last_bytenr-prevlog_bytes)) $logfile_last | "$awk_binary" -b "$awk_functions |
| 1037 |
BEGIN { |
| 1038 |
$awk_vars |
| 1039 |
lastTimestr = \"$lastTimestr\"; $scriptInitFromLastTimestr |
| 1040 |
}"' |
| 1041 |
'"$script1"' |
| 1042 |
( lastHHMM != curHHMM ) { |
| 1043 |
'"$scriptSetCurTimestr"'; |
| 1044 |
printIndexLine("'$indexfile'", curTimestr, NR+'$(( last_linenr-1 ))', bytenr_cur+'$(( last_bytenr-1 ))'); |
| 1045 |
printPercentage(bytenr_cur, '$size_to_index'); |
| 1046 |
'"$scriptSetLastTimestrEtc"' |
| 1047 |
} |
| 1048 |
' - |
| 1049 |
if [[ "$?" != 0 ]]; then |
| 1050 |
echo "debug:failed to index up, removing index file" 1>&2 |
| 1051 |
rm $indexfile |
| 1052 |
exit 1 |
| 1053 |
fi |
| 1054 |
else |
| 1055 |
echo "p:stage:$STAGE_INDEX_FULL:indexing from scratch" 1>&2 |
| 1056 |
|
| 1057 |
echo "prevlog_modtime $(get_file_modtime $logfile_prev)" > $indexfile |
| 1058 |
|
| 1059 |
"$awk_binary" -b "$awk_functions BEGIN { $awk_vars lastHHMM=\"\"; }"' |
| 1060 |
'"$script1"' |
| 1061 |
( lastHHMM != curHHMM ) { |
| 1062 |
'"$scriptSetCurTimestr"'; |
| 1063 |
printIndexLine("'$indexfile'", curTimestr, NR, bytenr_cur); |
| 1064 |
printPercentage(bytenr_cur, '$total_size'); |
| 1065 |
'"$scriptSetLastTimestrEtc"' |
| 1066 |
} |
| 1067 |
END { print "prevlog_lines\t" NR >> "'$indexfile'" } |
| 1068 |
' $logfile_prev |
| 1069 |
if [[ "$?" != 0 ]]; then |
| 1070 |
echo "debug:failed to index from scratch $logfile_prev, removing index file" 1>&2 |
| 1071 |
rm $indexfile |
| 1072 |
exit 1 |
| 1073 |
fi |
| 1074 |
|
| 1075 |
# Before we start handling $logfile_last, gotta read the last idx line (which is |
| 1076 |
# last-but-one line) and set it for the next script, otherwise there is a gap |
| 1077 |
# in index before the first line in the $logfile_last. |
| 1078 |
# TODO: make sure that if there are no logs in the $lotfile1, we don't screw up. |
| 1079 |
local lastTimestr="" |
| 1080 |
local lastTimestrLine="$(tail -n 2 $indexfile | head -n 1)" |
| 1081 |
if [[ "$lastTimestrLine" =~ ^idx$'\t' ]]; then |
| 1082 |
lastTimestr="$(echo "$lastTimestrLine" | cut -f2)" |
| 1083 |
fi |
| 1084 |
"$awk_binary" -b "$awk_functions BEGIN { $awk_vars lastTimestr = \"$lastTimestr\"; $scriptInitFromLastTimestr }"' |
| 1085 |
'"$script1"' |
| 1086 |
( lastHHMM != curHHMM ) { |
| 1087 |
'"$scriptSetCurTimestr"'; |
| 1088 |
bytenr = bytenr_cur+'$prevlog_bytes'; |
| 1089 |
printIndexLine("'$indexfile'", curTimestr, NR+'$(get_prevlog_lines_from_index)', bytenr); |
| 1090 |
printPercentage(bytenr, '$total_size'); |
| 1091 |
'"$scriptSetLastTimestrEtc"' |
| 1092 |
} |
| 1093 |
' $logfile_last |
| 1094 |
if [[ "$?" != 0 ]]; then |
| 1095 |
echo "debug:failed to index from scratch $logfile_last, removing index file" 1>&2 |
| 1096 |
rm $indexfile |
| 1097 |
exit 1 |
| 1098 |
fi |
| 1099 |
fi |
| 1100 |
} # }}} |
| 1101 |
|
| 1102 |
# Performs index lookup by a timestr like "2006-01-02-15:04" (typically given |
| 1103 |
# as --from or --to, and it's also stored in the index in the same form). |
| 1104 |
# |
| 1105 |
# Prints result: one of "found", "before" or "after"; and if the result |
| 1106 |
# is "found", then also prints linenumber and bytenumber, space-separated. |
| 1107 |
# "before" means the given timestr is earlier than the earliest log we have, |
| 1108 |
# and "after" obviously means that it's later than the latest log we have. |
| 1109 |
# |
| 1110 |
# One possible use is: |
| 1111 |
# read -r my_result my_linenr my_bytenr <<<$(get_linenr_and_bytenr_from_index my_timestr) |
| 1112 |
# |
| 1113 |
# Now we can use those vars $my_result, $my_linenr and $my_bytenr |
| 1114 |
function get_linenr_and_bytenr_from_index() { # {{{ |
| 1115 |
"$awk_binary" -F"\t" ' |
| 1116 |
BEGIN { isFirstIdx = 1; printed = 0; } |
| 1117 |
$1 == "idx" { |
| 1118 |
if ("'$1'" == $2) { |
| 1119 |
print "found " $3 " " $4; |
| 1120 |
printed = 1; |
| 1121 |
exit |
| 1122 |
} else if ("'$1'" < $2) { |
| 1123 |
if (isFirstIdx) { |
| 1124 |
print "before"; |
| 1125 |
} else { |
| 1126 |
print "found " $3 " " $4; |
| 1127 |
} |
| 1128 |
printed = 1; |
| 1129 |
exit |
| 1130 |
} else { |
| 1131 |
isFirstIdx = 0; |
| 1132 |
} |
| 1133 |
} |
| 1134 |
END { |
| 1135 |
if (!printed) { |
| 1136 |
print "after"; |
| 1137 |
} |
| 1138 |
} |
| 1139 |
' $indexfile |
| 1140 |
} # }}} |
| 1141 |
|
| 1142 |
function get_prevlog_lines_from_index() { # {{{ |
| 1143 |
if ! "$awk_binary" -F"\t" 'BEGIN { found=0 } $1 == "prevlog_lines" { print $2; found = 1; exit } END { if (found == 0) { exit 1 } }' $indexfile ; then |
| 1144 |
return 1 |
| 1145 |
fi |
| 1146 |
} # }}} |
| 1147 |
|
| 1148 |
function get_prevlog_modtime_from_index() { # {{{ |
| 1149 |
if ! "$awk_binary" -F"\t" 'BEGIN { found=0 } $1 == "prevlog_modtime" { print $2; found = 1; exit } END { if (found == 0) { exit 1 } }' $indexfile ; then |
| 1150 |
return 1 |
| 1151 |
fi |
| 1152 |
} # }}} |
| 1153 |
|
| 1154 |
function get_prevlog_bytenr() { # {{{ |
| 1155 |
get_file_size $logfile_prev |
| 1156 |
} # }}} |
| 1157 |
|
| 1158 |
is_outside_of_range=0 |
| 1159 |
if [[ "$from" != "" || "$to" != "" ]]; then |
| 1160 |
# If indexfile exists, check if it's valid and relevant; if not, delete it. |
| 1161 |
if [ -e "$indexfile" ]; then |
| 1162 |
# Check timestamp in the first line of /tmp/nerdlog_agent_index, and if |
| 1163 |
# $logfile_prev's modification time is newer, then delete whole index |
| 1164 |
logfile_prev_stored_modtime="$(get_prevlog_modtime_from_index)" |
| 1165 |
logfile_prev_cur_modtile=$(get_file_modtime $logfile_prev) |
| 1166 |
if [[ "$logfile_prev_stored_modtime" != "$logfile_prev_cur_modtile" ]]; then |
| 1167 |
echo "debug:prev logfile $logfile_prev has changed: stored '$logfile_prev_stored_modtime', actual '$logfile_prev_cur_modtile', deleting index file" 1>&2 |
| 1168 |
rm -f $indexfile || exit 1 |
| 1169 |
fi |
| 1170 |
|
| 1171 |
if ! get_prevlog_lines_from_index > /dev/null; then |
| 1172 |
echo "debug:broken index file (no prevlog lines), deleting it" 1>&2 |
| 1173 |
rm -f $indexfile || exit 1 |
| 1174 |
fi |
| 1175 |
fi |
| 1176 |
|
| 1177 |
refresh_and_retry=0 |
| 1178 |
|
| 1179 |
# First try to find it in index without refreshing the index |
| 1180 |
|
| 1181 |
if [ -s "$indexfile" ]; then |
| 1182 |
if [[ "$from" != "" ]]; then |
| 1183 |
read -r from_result from_linenr from_bytenr <<<$(get_linenr_and_bytenr_from_index "$from") || exit 1 |
| 1184 |
if [[ "$from_result" != "found" ]]; then |
| 1185 |
echo "debug:the from ${from} isn't found, gonna refresh the index" 1>&2 |
| 1186 |
refresh_and_retry=1 |
| 1187 |
fi |
| 1188 |
fi |
| 1189 |
|
| 1190 |
if [[ "$to" != "" ]]; then |
| 1191 |
read -r to_result to_linenr to_bytenr <<<$(get_linenr_and_bytenr_from_index "$to") || exit 1 |
| 1192 |
if [[ "$to_result" != "found" ]]; then |
| 1193 |
echo "debug:the to ${to} isn't found, gonna refresh the index" 1>&2 |
| 1194 |
refresh_and_retry=1 |
| 1195 |
fi |
| 1196 |
fi |
| 1197 |
else |
| 1198 |
echo "debug:index file doesn't exist or is empty, gonna refresh it" 1>&2 |
| 1199 |
refresh_and_retry=1 |
| 1200 |
fi |
| 1201 |
|
| 1202 |
if [[ "$refresh_and_retry" == 1 ]]; then |
| 1203 |
refresh_index || exit 1 |
| 1204 |
|
| 1205 |
if [[ "$from" != "" ]]; then |
| 1206 |
read -r from_result from_linenr from_bytenr <<<$(get_linenr_and_bytenr_from_index "$from") || exit 1 |
| 1207 |
|
| 1208 |
if [[ "$from_result" == "before" ]]; then |
| 1209 |
echo "debug:the from ${from} isn't found, will use the beginning" 1>&2 |
| 1210 |
elif [[ "$from_result" == "found" ]]; then |
| 1211 |
echo "debug:the from ${from} is found: $from_linenr ($from_bytenr)" 1>&2 |
| 1212 |
if [[ "$from_bytenr" == "" || "$from_linenr" == "" ]]; then |
| 1213 |
echo "error:from_result is found but from_bytenr and/or from_linenr is empty" 1>&2 |
| 1214 |
exit 1 |
| 1215 |
fi |
| 1216 |
elif [[ "$from_result" == "after" ]]; then |
| 1217 |
echo "debug:the from ${from} is after the latest log we have, will return nothing" 1>&2 |
| 1218 |
is_outside_of_range=1 |
| 1219 |
else |
| 1220 |
echo "error:invalid from_result: $from_result" 1>&2 |
| 1221 |
exit 1 |
| 1222 |
fi |
| 1223 |
fi |
| 1224 |
|
| 1225 |
if [[ "$to" != "" ]]; then |
| 1226 |
read -r to_result to_linenr to_bytenr <<<$(get_linenr_and_bytenr_from_index "$to") || exit 1 |
| 1227 |
|
| 1228 |
if [[ "$to_result" == "after" ]]; then |
| 1229 |
echo "debug:the to ${to} isn't found, will use the end" 1>&2 |
| 1230 |
elif [[ "$to_result" == "found" ]]; then |
| 1231 |
echo "debug:the to ${to} is found: $to_linenr ($to_bytenr)" 1>&2 |
| 1232 |
if [[ "$to_bytenr" == "" || "$to_linenr" == "" ]]; then |
| 1233 |
echo "error:to_result is found but to_bytenr and/or to_linenr is empty" 1>&2 |
| 1234 |
exit 1 |
| 1235 |
fi |
| 1236 |
elif [[ "$to_result" == "before" ]]; then |
| 1237 |
echo "debug:the to ${to} is before the first log we have, will return nothing" 1>&2 |
| 1238 |
is_outside_of_range=1 |
| 1239 |
else |
| 1240 |
echo "error:invalid to_result: $to_result" 1>&2 |
| 1241 |
exit 1 |
| 1242 |
fi |
| 1243 |
fi |
| 1244 |
|
| 1245 |
fi |
| 1246 |
else |
| 1247 |
if ! [ -s $indexfile ]; then |
| 1248 |
echo "debug:neither --from or --to are given, but index doesn't exist at all, gonna rebuild" 1>&2 |
| 1249 |
refresh_index || exit 1 |
| 1250 |
fi |
| 1251 |
fi |
| 1252 |
|
| 1253 |
if [[ $is_outside_of_range == 1 ]]; then |
| 1254 |
echo "p:stage:$STAGE_DONE:done" 1>&2 |
| 1255 |
exit 0 |
| 1256 |
fi |
| 1257 |
|
| 1258 |
echo "p:stage:$STAGE_QUERYING:querying logs" 1>&2 |
| 1259 |
|
| 1260 |
prevlog_lines=$(get_prevlog_lines_from_index) |
| 1261 |
prevlog_bytes=$(get_prevlog_bytenr) |
| 1262 |
|
| 1263 |
from_linenr_int=$from_linenr |
| 1264 |
if [[ "$from_linenr" == "" ]]; then |
| 1265 |
from_linenr_int=1 |
| 1266 |
fi |
| 1267 |
|
| 1268 |
lines_until_check='' |
| 1269 |
if [[ "$lines_until" != "" ]]; then |
| 1270 |
lines_until_check="if (NR >= $((lines_until-from_linenr_int+1))) { next; }" |
| 1271 |
fi |
| 1272 |
|
| 1273 |
num_bytes_to_scan=0 |
| 1274 |
if [[ "$from_bytenr" == "" && "$to_bytenr" == "" ]]; then |
| 1275 |
# Getting _all_ available logs |
| 1276 |
num_bytes_to_scan=$total_size |
| 1277 |
elif [[ "$from_bytenr" != "" && "$to_bytenr" == "" ]]; then |
| 1278 |
# Getting logs from some point in time to the very end (most frequent case) |
| 1279 |
num_bytes_to_scan=$((total_size-from_bytenr)) |
| 1280 |
elif [[ "$from_bytenr" == "" && "$to_bytenr" != "" ]]; then |
| 1281 |
# Getting logs from the beginning until some point in time |
| 1282 |
num_bytes_to_scan=$((to_bytenr)) |
| 1283 |
else |
| 1284 |
# Getting logs between two points T1 and T2 |
| 1285 |
num_bytes_to_scan=$((to_bytenr-from_bytenr)) |
| 1286 |
fi |
| 1287 |
|
| 1288 |
|
| 1289 |
# NOTE: there are multiple ways to tail a file, and performance differs greatly: |
| 1290 |
# Log file has 21789347 lines: |
| 1291 |
# |
| 1292 |
#ubuntu@dummy-node-01:~$ time cat /var/log/syslog.1 | tail -n +16789340 > /dev/null |
| 1293 |
|
| 1294 |
#real 0m4.523s |
| 1295 |
#user 0m0.869s |
| 1296 |
#sys 0m6.915s |
| 1297 |
#ubuntu@dummy-node-01:~$ time tail -n +16789340 /var/log/syslog.1 > /dev/null |
| 1298 |
|
| 1299 |
#real 0m2.184s |
| 1300 |
#user 0m0.660s |
| 1301 |
#sys 0m1.524s |
| 1302 |
#ubuntu@dummy-node-01:~$ time tail -n 5000000 /var/log/syslog.1 > /dev/null |
| 1303 |
|
| 1304 |
#real 0m1.260s |
| 1305 |
#user 0m0.412s |
| 1306 |
#sys 0m0.848s |
| 1307 |
|
| 1308 |
# So it's best to tail file directly (without cat) and also whenever possible |
| 1309 |
# do the "-n N", not "-n +N" (but for the latest logfile, which is constantly |
| 1310 |
# appended to, we have to use the "-n +N") |
| 1311 |
|
| 1312 |
# Generate commands to get all the logs as per requested timerange. |
| 1313 |
declare -a cmds |
| 1314 |
if [[ "$from_bytenr" != "" && $(( from_bytenr > prevlog_bytes )) == 1 ]]; then |
| 1315 |
# Only $logfile_last is used. |
| 1316 |
from_bytenr=$(( from_bytenr - prevlog_bytes )) |
| 1317 |
if [[ "$to_bytenr" != "" ]]; then |
| 1318 |
to_bytenr=$(( to_bytenr - prevlog_bytes )) |
| 1319 |
echo "debug:Getting logs from offset $from_bytenr, only $((to_bytenr - from_bytenr)) bytes, all in the latest $logfile_last" 1>&2 |
| 1320 |
cmds+=("tail -c +$from_bytenr $logfile_last | head -c $((to_bytenr - from_bytenr))") |
| 1321 |
else |
| 1322 |
# Most common case |
| 1323 |
echo "debug:Getting logs from offset $from_bytenr until the end of latest $logfile_last." 1>&2 |
| 1324 |
cmds+=("tail -c +$from_bytenr $logfile_last") |
| 1325 |
fi |
| 1326 |
elif [[ "$to_bytenr" != "" && $(( to_bytenr <= prevlog_bytes )) == 1 ]]; then |
| 1327 |
# Only $logfile_prev is used. |
| 1328 |
if [[ "$from_bytenr" != "" ]]; then |
| 1329 |
echo "debug:Getting logs from offset $from_bytenr, only $((to_bytenr - from_bytenr)) bytes, all in the prev $logfile_prev" 1>&2 |
| 1330 |
cmds+=("tail -c +$from_bytenr $logfile_prev | head -c $((to_bytenr - from_bytenr))") |
| 1331 |
else |
| 1332 |
echo "debug:Getting logs from the very beginning to offset $(( to_bytenr - 1 )), all in the prev $logfile_prev." 1>&2 |
| 1333 |
cmds+=("head -c $(( to_bytenr - 1)) $logfile_prev") |
| 1334 |
fi |
| 1335 |
else |
| 1336 |
# Both log files are used |
| 1337 |
if [[ "$from_bytenr" != "" ]]; then |
| 1338 |
info="Getting logs from offset $from_bytenr in prev $logfile_prev" |
| 1339 |
cmds+=("tail -c +$from_bytenr $logfile_prev") |
| 1340 |
else |
| 1341 |
info="Getting logs from the very beginning in prev $logfile_prev" |
| 1342 |
cmds+=("cat $logfile_prev") |
| 1343 |
fi |
| 1344 |
|
| 1345 |
if [[ "$to_bytenr" != "" ]]; then |
| 1346 |
info="$info to offset $(( to_bytenr - prevlog_bytes - 1 )) in latest $logfile_last" |
| 1347 |
cmds+=("head -c $(( to_bytenr - prevlog_bytes - 1 )) $logfile_last") |
| 1348 |
else |
| 1349 |
info="$info until the end of latest $logfile_last" |
| 1350 |
cmds+=("cat $logfile_last") |
| 1351 |
fi |
| 1352 |
|
| 1353 |
echo "debug:$info" 1>&2 |
| 1354 |
fi |
| 1355 |
|
| 1356 |
cmds_concatenated="$(concat_cmds_array)" |
| 1357 |
echo "debug:Command to filter logs by time range:" 1>&2 |
| 1358 |
echo "debug: bash -c '$cmds_concatenated'" 1>&2 |
| 1359 |
|
| 1360 |
# Now execute all those commands, and feed those logs to the awk script |
| 1361 |
# which will analyze them and produce the final output. |
| 1362 |
eval $cmds_concatenated | \ |
| 1363 |
user_pattern="$user_pattern" \ |
| 1364 |
max_num_lines="$max_num_lines" \ |
| 1365 |
num_bytes_to_scan="$num_bytes_to_scan" \ |
| 1366 |
lines_until_check="$lines_until_check" \ |
| 1367 |
prevlog_lines="$prevlog_lines" \ |
| 1368 |
from_linenr_int="$from_linenr_int" \ |
| 1369 |
run_awk_script_logfiles - |
| 1370 |
|
| 1371 |
codes=(${PIPESTATUS[@]}) |
| 1372 |
for status in "${codes[@]}"; do |
| 1373 |
if [[ $status -ne 0 ]]; then |
| 1374 |
exit 1 |
| 1375 |
fi |
| 1376 |
done |
| 1377 |
|
| 1378 |
echo "p:stage:$STAGE_DONE:done" 1>&2 |