From f5117b745a3d8512d82d98ff614439985a31b27e Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Sun, 6 Dec 2026 10:02:39 -0500 Subject: [PATCH] Add the Log Analyzer concept exercise for pipelines Five tasks investigate a web-service log file with pipelines, then practice the && and || command-list operators and exit statuses. The exercise is listed in config.json as wip and in the road map. Co-Authored-By: Claude Sonnet 5.5 --- config.json | 12 + exercises/concept/log-analyzer/.docs/hints.md | 49 ++ .../log-analyzer/.docs/instructions.md | 89 +++ .../log-analyzer/.docs/introduction.md | 200 ++++++ .../log-analyzer/.docs/introduction.md.tpl | 3 + .../concept/log-analyzer/.meta/config.json | 20 + .../concept/log-analyzer/.meta/design.md | 34 + .../concept/log-analyzer/.meta/exemplar.sh | 35 + .../concept/log-analyzer/bats-extra.bash | 642 ++++++++++++++++++ .../concept/log-analyzer/log_analyzer.bats | 158 +++++ .../concept/log-analyzer/log_analyzer.sh | 62 ++ exercises/concept/road-map.md | 2 +- 12 files changed, 1305 insertions(+), 1 deletion(-) create mode 100644 exercises/concept/log-analyzer/.docs/hints.md create mode 100644 exercises/concept/log-analyzer/.docs/instructions.md create mode 100644 exercises/concept/log-analyzer/.docs/introduction.md create mode 100644 exercises/concept/log-analyzer/.docs/introduction.md.tpl create mode 100644 exercises/concept/log-analyzer/.meta/config.json create mode 100644 exercises/concept/log-analyzer/.meta/design.md create mode 100644 exercises/concept/log-analyzer/.meta/exemplar.sh create mode 100644 exercises/concept/log-analyzer/bats-extra.bash create mode 100644 exercises/concept/log-analyzer/log_analyzer.bats create mode 100644 exercises/concept/log-analyzer/log_analyzer.sh diff --git a/config.json b/config.json index a2f49699..ed64bc57 100644 --- a/config.json +++ b/config.json @@ -115,6 +115,18 @@ "conditionals" ], "status": "wip" + }, + { + "slug": "log-analyzer", + "name": "Log Analyzer", + "uuid": "98697acc-298c-4eb1-9332-f7ac78e42b93", + "concepts": [ + "pipelines" + ], + "prerequisites": [ + "quoting" + ], + "status": "wip" } ], "practice": [ diff --git a/exercises/concept/log-analyzer/.docs/hints.md b/exercises/concept/log-analyzer/.docs/hints.md new file mode 100644 index 00000000..971f3e4e --- /dev/null +++ b/exercises/concept/log-analyzer/.docs/hints.md @@ -0,0 +1,49 @@ +# Hints + +## General + +- Read about [pipelines][pipelines] and [lists of commands][lists] in the bash manual, or the track's pipelines concept page. +- Each command in a pipeline reads the output of the command before it. +- The commands `grep`, `cut`, `sort`, `uniq`, `head` and `tail` each do one small job. + Read their manual pages to find the options you need. +- Try each pipeline one command at a time. + Add the next command only when the output so far looks right. + +## 1. List the sources of the errors + +- Keep only the lines that have `ERROR` as the level. +- Use `cut` to select a field, and tell it which character separates the fields. +- `sort` has an option to remove duplicate lines. + +## 2. Find the most common level + +- Start by selecting the level of each entry. +- `uniq` only compares lines that are next to each other, so sort the lines first. +- `uniq` can count the lines that it combines. + That puts the count in front of each line, after some spaces. +- Sort the counted lines again, this time by number, so that the biggest count comes first. +- `head` takes lines from the start of its input. +- Take the count off the line. + `tr` can squeeze repeated spaces into one, and then `cut` can select a field. + +## 3. Show the recent errors + +- Start with the same `grep` as in the first task. +- `tail` takes lines from the end of its input, and its option takes the number of lines to take. +- To print the source and the message, `cut` can select a range of fields: a number followed by a dash selects that field and every field after it. + +## 4. Raise the alarm + +- `grep` has an option that makes it print nothing, and only report in its exit status if it found a match. +- The `&&` operator runs the next command only if the previous one succeeded. +- The exit status of a list of commands is the exit status of the last command that ran. + If `grep` finds nothing, its exit status is not zero. + +## 5. Check the log file + +- Use the same quiet `grep` as in the previous task, with an option that lets one pattern match either word. +- The `||` operator runs the next command only if the previous one failed. +- The `exit` command ends the script, and its argument is the exit status. + +[pipelines]: https://www.gnu.org/software/bash/manual/html_node/Pipelines.html +[lists]: https://www.gnu.org/software/bash/manual/html_node/Lists.html diff --git a/exercises/concept/log-analyzer/.docs/instructions.md b/exercises/concept/log-analyzer/.docs/instructions.md new file mode 100644 index 00000000..02eab164 --- /dev/null +++ b/exercises/concept/log-analyzer/.docs/instructions.md @@ -0,0 +1,89 @@ +# Instructions + +You are the on-call engineer for a web service, and you want a script to help you investigate its log file. + +Each line of the log file is one entry. +The fields of an entry are separated by single spaces: + +```text +2024-03-01 08:00:05 ERROR db connection lost +``` + +- The first field is the date, and the second is the time. +- The third is the _level_ of the entry: `INFO`, `WARN`, `ERROR` or `CRITICAL`. +- The fourth is the _source_, the name of the part of the service that wrote the entry. +- The rest of the line is the message, which is made up of one or more words. + +You have five tasks, and they all belong to the same script. +The first argument names the task to perform, and the first of the remaining arguments is always the name of the log file. +The script you are given already runs the right part of the code for each task, so you only need to fill in each part. +The log file name may contain spaces, so remember to quote it. + +Ordinary text tools such as `grep`, `cut`, `sort`, `uniq`, `head` and `tail` are all you need. + +~~~~exercism/note +You may already know a powerful tool such as `awk`. +The purpose of this exercise is to practice building pipelines, so stick to the simpler tools. +~~~~ + +Do not print anything other than the requested output. + +## 1. List the sources of the errors + +Print the name of each source that logged at least one `ERROR` entry. +Print one name per line, in alphabetical order, and print each name only once. + +```text +$ bash log_analyzer.sh error-sources service.log +cache +db +web +``` + +## 2. Find the most common level + +Print the level that is used by the greatest number of entries. +You can assume that there is only one such level. + +```text +$ bash log_analyzer.sh common-level service.log +INFO +``` + +## 3. Show the recent errors + +The second argument is a number. +Print the source and the message of that many `ERROR` entries, taken from the end of the log file. +Print them in the order in which they appear in the log file. +If there are fewer `ERROR` entries than that, print all of them. + +```text +$ bash log_analyzer.sh recent-errors service.log 2 +db query failed +cache eviction failed +``` + +## 4. Raise the alarm + +If the log file has any `CRITICAL` entry, print `page the on-call engineer`. +Otherwise, print nothing. + +In both cases, the script must exit with status 0. + +```text +$ bash log_analyzer.sh alert service.log +$ echo $? +0 +``` + +## 5. Check the log file + +If the log file has any `ERROR` entry or any `CRITICAL` entry, print `problems found` and exit with status 1. +Otherwise, print nothing and exit with status 0. + +```text +$ bash log_analyzer.sh check service.log +problems found +$ echo $? +1 +``` diff --git a/exercises/concept/log-analyzer/.docs/introduction.md b/exercises/concept/log-analyzer/.docs/introduction.md new file mode 100644 index 00000000..7bccd34a --- /dev/null +++ b/exercises/concept/log-analyzer/.docs/introduction.md @@ -0,0 +1,200 @@ +# Introduction + +## Pipelines and Command Lists + +We have seen how to write simple commands, where a command is followed by arguments. +Now we will see how to make more complex commands by composing simple commands. + +### Input and Output + +Before we start, a quick introduction to input/output. + +Processes have "standard I/O channels". + +* A process can consume _input_ on "stdin". +* A process can emit _output_ on "stdout". +* A process can emit _error output_ on "stderr". + +The `tr` command is a very pure example of this. +All it does is read text from its input, perform character transliterations, and print the resulting text to its output. + +We will see more about manipulating "stdio" channels later in the syllabus. + +### Pipelines + +This is one of the "killer features" of shell programming. +Pipelines allow you create sophisticated transformations on a stream of text. + +To produce a sorted list of users: + +```bash +cat /etc/passwd | cut -d : -f 1 | sort +``` + +The pipe symbol (`|`) connects the output of one command to the input of another. +`cut` reads the output of `cat`, and `sort` reads the output of `cut`. + +~~~~exercism/advanced +* By default, each command in a pipeline runs in a separate subshell. + (A subshell is a child process that is a copy of the currently running shell.) + +* There is a performance cost to running pipelines. + If you find yourself with long pipelines of similar commands, consider combining them in a single command. + For example, pipelines using multiple instances of `grep`, `cut`, `sed`, `awk`, and `tr` can generally be combined into a single `awk` command for efficiency. + +* The exit status of a pipeline is the exit status of the last command in the pipeline. + That means if some earlier command failed but the last command succeeded, the exit status of the whole pipline is zero. + + There is a shell setting that can change this; + if the "pipefail" setting is enabled (with `set -o pipefail`) then the pipeline's exit status will be: + * zero if all commands succeed, otherwise + * the _**last** non-zero exit status_ of the commands in the pipeline. +~~~~ + +### Command Lists + +A command list is a sequence of pipelines separated by `;` (or newline), `&&` or `||`. + +* `A; B` is a command list where `B` executes after `A` has completed. +* `A && B`, where `B` executes only if `A` succeeds (exits with status zero). +* `A || B`, where `B` executes only if `A` fails (exits with status non-zero). + +The exit status of a command list is the exit status of the last command that was executed. + +The `&&` and `||` operators can be chained so that the next command conditionally executes based on the status of the preceding commands. +For example + +```bash +A && B && C && D || E +``` + +* B executes if A succeeds, +* C executes if A and B succeed, +* D executes if A and B and C succeed, +* E executes if **any** of A, B, C or D fails. + +~~~~exercism/caution +Use these logical operators sparingly. +They can quickly lead to unreadable code, or logic that is hard to comprehend. + +For example, you may think these are the same: + +```bash +if A; then B; else C; fi +``` + +```bash +A && B || C +``` + +The difference is: when does C execute? + +* In the first snippet (the if statement), C will execute only if A fails. +* In the second snippet, C will execute if A fails _or if A succeeds but B fails_! +~~~~ + +#### Uses of Command Lists + +Here are a couple of examples where command lists can simplify the code. + +##### Reading blocks of lines from a file + +Suppose you have a data file containing data about triangles, +and a triangle is represented by three separate lines holding the sides of the triangle. + +```bash +$ cat triangle.dat +3 +4 +5 +9 +12 +14 +``` + +You can use a while loop where the condition is three separate read commands: + +```bash +while read a && read b && read c; do + if is_pythagorean "$a" "$b" "$c"; then + echo "$a:$b:$c is pythagorean" + else + echo "$a:$b:$c is not pythagorean" + fi +done < triangle.dat +``` + +Assuming `is_pythagorean` is a command that determines if the three sides satisfy the Pythagoran equation, the output would be: + +```none +3:4:5 is pythagorean +9:12:14 is not pythagorean +``` + +##### Assertions + +Many programming languages have a form of assertion where an exception is thrown if some condition fails + +``` +assert(user == "Administrator", "wrong user"); +``` + +We can use an OR operator in Bash to simulate that function: + +```bash +die () { # a little convenience function + echo "$*" >&2 + exit 1 +} + +[[ $user == "Administrator" ]] || die "wrong user" +[[ $password == "secret!" ]] || die "incorrect password" +``` + +### Style Considerations + +Long command lists become hard to read quite quickly. +Liberal use of newlines can help a lot. + +Consider this example where a word is added to an array if two conditions are met. + +```bash +[[ "$word" != "$topic" ]] && [[ "$key" == "$(sorted "$topic")" ]] && anagrams+=("$candidate") +``` + +Bash allows you to add a newline after a pipe or a logical operator. + +```bash +[[ "$word" != "$topic" ]] && +[[ "$key" == "$(sorted "$topic")" ]] && +anagrams+=("$candidate") +``` + +However, the operator can be easy to miss at the end of the line. +Using a _line continuation_ means you can put the operator first, which makes it more obvious that the list is being continued: + +```bash +[[ "$word" != "$topic" ]] \ +&& [[ "$key" == "$(sorted "$topic")" ]] \ +&& anagrams+=("$candidate") +``` + +~~~~exercism/note +A _line continuation_ is the two character sequence "backslash" and "newline" (`\` + `\n`). +When Bash sees that sequence, it is simply removed from the code, thereby _continuing_ the current line with the next line. +Take care to not allow any spaces between the backslash and the newline. +~~~~ + +Here's another example + +```bash +printf "%s\n" "${numbers[@]}" | bc --mathlib | sort --general-numeric-sort +``` + +or + +```bash +printf "%s\n" "${numbers[@]}" \ +| bc --mathlib \ +| sort --general-numeric-sort +``` diff --git a/exercises/concept/log-analyzer/.docs/introduction.md.tpl b/exercises/concept/log-analyzer/.docs/introduction.md.tpl new file mode 100644 index 00000000..0879ad7a --- /dev/null +++ b/exercises/concept/log-analyzer/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:pipelines} diff --git a/exercises/concept/log-analyzer/.meta/config.json b/exercises/concept/log-analyzer/.meta/config.json new file mode 100644 index 00000000..94a655dd --- /dev/null +++ b/exercises/concept/log-analyzer/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "log_analyzer.sh" + ], + "test": [ + "log_analyzer.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "blurb": "Learn about pipelines and command lists while investigating the log file of a web service." +} diff --git a/exercises/concept/log-analyzer/.meta/design.md b/exercises/concept/log-analyzer/.meta/design.md new file mode 100644 index 00000000..ca242a47 --- /dev/null +++ b/exercises/concept/log-analyzer/.meta/design.md @@ -0,0 +1,34 @@ +# Design + +## Goal + +The goal of this exercise is to introduce pipelines and command lists. + +## Learning objectives + +- Connect commands with the pipe symbol, `|`, to transform a stream of text. +- Chain several commands, each reading the output of the one before it. +- Use the output of `uniq -c` and `sort` to find the most frequent value. +- Run a command only if the previous one succeeds, with `&&`. +- Run a command only if the previous one fails, with `||`. +- Know that the exit status of a command list is the exit status of the last command that was executed. + +## Out of scope + +- The `pipefail` option, and subshells. +- Redirection, including reading the standard input of the script. +- Functions, including a `die` function. +- Grouping commands with `{ ...; }`. +- Combining `&&` and `||` in the form `A && B || C`. +- Combining a pipeline of text tools into a single `awk` command. +- Validating the input. + +## Concepts + +The Concepts this exercise unlocks are: + +- `pipelines` + +## Prerequisites + +- `quoting` diff --git a/exercises/concept/log-analyzer/.meta/exemplar.sh b/exercises/concept/log-analyzer/.meta/exemplar.sh new file mode 100644 index 00000000..5d346046 --- /dev/null +++ b/exercises/concept/log-analyzer/.meta/exemplar.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash + +task=$1 +shift + +case $task in + error-sources) + grep ' ERROR ' "$1" | cut -d ' ' -f 4 | sort -u + ;; + + common-level) + cut -d ' ' -f 3 "$1" \ + | sort \ + | uniq -c \ + | sort -rn \ + | head -n 1 \ + | tr -s ' ' \ + | cut -d ' ' -f 3 + ;; + + recent-errors) + grep ' ERROR ' "$1" | tail -n "$2" | cut -d ' ' -f 4- + ;; + + alert) + grep -q ' CRITICAL ' "$1" && echo 'page the on-call engineer' + exit 0 + ;; + + check) + grep -q -E ' (ERROR|CRITICAL) ' "$1" || exit 0 + echo 'problems found' + exit 1 + ;; +esac diff --git a/exercises/concept/log-analyzer/bats-extra.bash b/exercises/concept/log-analyzer/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/log-analyzer/bats-extra.bash @@ -0,0 +1,642 @@ +# This is the source code for bats-support and bats-assert, concatenated +# * https://github.com/bats-core/bats-support +# * https://github.com/bats-core/bats-assert +# +# Comments have been removed to save space. See the git repos for full source code. + +############################################################ +# +# bats-support - Supporting library for Bats test helpers +# +# Written in 2016 by Zoltan Tombol +# +# To the extent possible under law, the author(s) have dedicated all +# copyright and related and neighboring rights to this software to the +# public domain worldwide. This software is distributed without any +# warranty. +# +# You should have received a copy of the CC0 Public Domain Dedication +# along with this software. If not, see +# . +# + +# shellcheck disable=SC2120 # (warning): fail references arguments, but none are ever passed. +fail() { + # shellcheck disable=2015 # (info): Note that A && B || C is not if-then-else. C may run when A is true. + (( $# == 0 )) && batslib_err || batslib_err "$@" + return 1 +} + +batslib_is_caller() { + local -i is_mode_direct=1 + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -i|--indirect) is_mode_direct=0; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + # Arguments. + local -r func="$1" + + # Check call stack. + if (( is_mode_direct )); then + [[ $func == "${FUNCNAME[2]}" ]] && return 0 + else + local -i depth + for (( depth=2; depth<${#FUNCNAME[@]}; ++depth )); do + [[ $func == "${FUNCNAME[$depth]}" ]] && return 0 + done + fi + + return 1 +} + +batslib_err() { + { if (( $# > 0 )); then + echo "$@" + else + cat - + fi + } >&2 +} + +batslib_count_lines() { + local -i n_lines=0 + local line + while IFS='' read -r line || [[ -n $line ]]; do + (( ++n_lines )) + done < <(printf '%s' "$1") + echo "$n_lines" +} + +batslib_is_single_line() { + for string in "$@"; do + (( $(batslib_count_lines "$string") > 1 )) && return 1 + done + return 0 +} + +batslib_get_max_single_line_key_width() { + local -i max_len=-1 + while (( $# != 0 )); do + local -i key_len="${#1}" + batslib_is_single_line "$2" && (( key_len > max_len )) && max_len="$key_len" + shift 2 + done + echo "$max_len" +} + +batslib_print_kv_single() { + local -ir col_width="$1"; shift + while (( $# != 0 )); do + printf '%-*s : %s\n' "$col_width" "$1" "$2" + shift 2 + done +} + +batslib_print_kv_multi() { + while (( $# != 0 )); do + printf '%s (%d lines):\n' "$1" "$( batslib_count_lines "$2" )" + printf '%s\n' "$2" + shift 2 + done +} + +batslib_print_kv_single_or_multi() { + local -ir width="$1"; shift + local -a pairs=( "$@" ) + + local -a values=() + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + values+=( "${pairs[$i]}" ) + done + + if batslib_is_single_line "${values[@]}"; then + batslib_print_kv_single "$width" "${pairs[@]}" + else + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + pairs[i]="$( batslib_prefix < <(printf '%s' "${pairs[$i]}") )" + done + batslib_print_kv_multi "${pairs[@]}" + fi +} + +batslib_prefix() { + local -r prefix="${1:- }" + local line + while IFS='' read -r line || [[ -n $line ]]; do + printf '%s%s\n' "$prefix" "$line" + done +} + +batslib_mark() { + local -r symbol="$1"; shift + # Sort line numbers. + # shellcheck disable=SC2046 # (warning): Quote this to prevent word splitting. + set -- $( sort -nu <<< "$( printf '%d\n' "$@" )" ) + + local line + local -i idx=0 + while IFS='' read -r line || [[ -n $line ]]; do + if (( ${1:--1} == idx )); then + printf '%s\n' "${symbol}${line:${#symbol}}" + shift + else + printf '%s\n' "$line" + fi + (( ++idx )) + done +} + +batslib_decorate() { + echo + echo "-- $1 --" + cat - + echo '--' + echo +} + +############################################################ + +assert() { + if ! "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion failed' \ + | fail + fi +} + +assert_equal() { + if [[ $1 != "$2" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$2" \ + 'actual' "$1" \ + | batslib_decorate 'values do not equal' \ + | fail + fi +} + +assert_failure() { + : "${output?}" + : "${status?}" + + (( $# > 0 )) && local -r expected="$1" + if (( status == 0 )); then + batslib_print_kv_single_or_multi 6 'output' "$output" \ + | batslib_decorate 'command succeeded, but it was expected to fail' \ + | fail + elif (( $# > 0 )) && (( status != expected )); then + { local -ir width=8 + batslib_print_kv_single "$width" \ + 'expected' "$expected" \ + 'actual' "$status" + batslib_print_kv_single_or_multi "$width" \ + 'output' "$output" + } \ + | batslib_decorate 'command failed as expected, but status differs' \ + | fail + fi +} + +assert_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Arguments. + local -r expected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $expected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if ! [[ ${lines[$idx]} =~ $expected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression does not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} != *"$expected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line does not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} != "$expected" ]]; then + batslib_print_kv_single 8 \ + 'index' "$idx" \ + 'expected' "$expected" \ + 'actual' "${lines[$idx]}" \ + | batslib_decorate 'line differs' \ + | fail + fi + fi + else + # Contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} =~ $expected ]] && return 0 + done + { local -ar single=( 'regexp' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line matches regular expression' \ + | fail + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == *"$expected"* ]] && return 0 + done + { local -ar single=( 'substring' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line contains substring' \ + | fail + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == "$expected" ]] && return 0 + done + { local -ar single=( 'line' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'output does not contain line' \ + | fail + fi + fi +} + +assert_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_nonempty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_nonempty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + return $? + fi + + # Arguments. + local expected + if (( use_stdin )); then + expected="$(cat -)" + else + expected="${1-}" + fi + + # Matching. + if (( is_mode_nonempty )); then + if [ -z "$output" ]; then + echo 'expected non-empty output, but output was empty' \ + | batslib_decorate 'no output' \ + | fail + fi + elif (( is_mode_regexp )); then + # shellcheck disable=SC2319 # (warning) `$?` in a conditional expression: https://github.com/koalaman/shellcheck/wiki/SC2319 + if [[ '' =~ $expected ]] || (( $? == 2 )); then + # the regex matches an empty string or it is syntactically incorrect. + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + elif ! [[ $output =~ $expected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression does not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output != *"$expected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'output does not contain substring' \ + | fail + fi + else + if [[ $output != "$expected" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$expected" \ + 'actual' "$output" \ + | batslib_decorate 'output differs' \ + | fail + fi + fi +} + +assert_success() { + : "${output?}" + : "${status?}" + + if (( status != 0 )); then + { local -ir width=6 + batslib_print_kv_single "$width" 'status' "$status" + batslib_print_kv_single_or_multi "$width" 'output' "$output" + } \ + | batslib_decorate 'command failed' \ + | fail + fi +} + +refute() { + if "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion succeeded, but it was expected to fail' \ + | fail + fi +} + +refute_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Arguments. + local -r unexpected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if [[ ${lines[$idx]} =~ $unexpected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression should not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} == "$unexpected" ]]; then + batslib_print_kv_single 5 \ + 'index' "$idx" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should differ' \ + | fail + fi + fi + else + # Line contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} =~ $unexpected ]]; then + { local -ar single=( 'regexp' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should match the regular expression' \ + | fail + return $? + fi + done + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + { local -ar single=( 'substring' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should contain substring' \ + | fail + return $? + fi + done + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == "$unexpected" ]]; then + { local -ar single=( 'line' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'line should not be in output' \ + | fail + return $? + fi + done + fi + fi +} + +refute_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_empty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_empty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Arguments. + local unexpected + if (( use_stdin )); then + unexpected="$(cat -)" + else + unexpected="${1-}" + fi + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Matching. + if (( is_mode_empty )); then + if [ -n "$output" ]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output non-empty, but expected no output' \ + | fail + fi + elif (( is_mode_regexp )); then + if [[ $output =~ $unexpected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression should not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output == *"$unexpected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'output should not contain substring' \ + | fail + fi + else + if [[ $output == "$unexpected" ]]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output equals, but it was expected to differ' \ + | fail + fi + fi +} diff --git a/exercises/concept/log-analyzer/log_analyzer.bats b/exercises/concept/log-analyzer/log_analyzer.bats new file mode 100644 index 00000000..4d181cca --- /dev/null +++ b/exercises/concept/log-analyzer/log_analyzer.bats @@ -0,0 +1,158 @@ +#!/usr/bin/env bats +load bats-extra + +setup() { + BUSY_LOG=$BATS_TEST_TMPDIR/busy.log + CRITICAL_LOG=$BATS_TEST_TMPDIR/critical.log + QUIET_LOG=$BATS_TEST_TMPDIR/quiet.log + + cat > "$BUSY_LOG" << 'END' +2024-03-01 08:00:01 INFO web request served +2024-03-01 08:00:05 ERROR db connection lost +2024-03-01 08:01:10 INFO web request served +2024-03-01 08:02:30 WARN cache entry expired +2024-03-01 08:03:00 ERROR web timeout waiting for upstream +2024-03-01 08:03:15 INFO db reconnected +2024-03-01 08:04:00 ERROR db query failed +2024-03-01 08:05:00 INFO web request served +2024-03-01 08:06:00 ERROR cache eviction failed +2024-03-01 08:07:00 INFO web request served +END + + cat > "$CRITICAL_LOG" << 'END' +2024-03-02 21:00:00 INFO web request served +2024-03-02 21:00:09 CRITICAL db disk is full +2024-03-02 21:00:10 ERROR web request failed +2024-03-02 21:00:11 ERROR db replica lagging +END + + cat > "$QUIET_LOG" << 'END' +2024-03-03 12:00:00 INFO web request served +2024-03-03 12:00:30 WARN cache entry expired +2024-03-03 12:01:00 INFO web request served +END +} + +# bats test_tags=task:1 +test_error_sources_lists_each_source_once_in_order() { # @test + run bash log_analyzer.sh error-sources "$BUSY_LOG" + + assert_success + assert_output $'cache\ndb\nweb' +} + +# bats test_tags=task:1 +test_error_sources_ignores_other_levels() { # @test + run bash log_analyzer.sh error-sources "$CRITICAL_LOG" + + assert_success + assert_output $'db\nweb' +} + +# bats test_tags=task:1 +test_error_sources_without_errors() { # @test + run bash log_analyzer.sh error-sources "$QUIET_LOG" + + assert_success + assert_output '' +} + +# bats test_tags=task:1 +test_error_sources_with_spaces_in_the_file_name() { # @test + local dir="$BATS_TEST_TMPDIR/my logs" + mkdir "$dir" + cp "$BUSY_LOG" "$dir/busy log.log" + + run bash log_analyzer.sh error-sources "$dir/busy log.log" + + assert_success + assert_output $'cache\ndb\nweb' +} + +# bats test_tags=task:2 +test_common_level_in_busy_log() { # @test + run bash log_analyzer.sh common-level "$BUSY_LOG" + + assert_success + assert_output 'INFO' +} + +# bats test_tags=task:2 +test_common_level_in_critical_log() { # @test + run bash log_analyzer.sh common-level "$CRITICAL_LOG" + + assert_success + assert_output 'ERROR' +} + +# bats test_tags=task:3 +test_recent_errors_last_one() { # @test + run bash log_analyzer.sh recent-errors "$BUSY_LOG" 1 + + assert_success + assert_output 'cache eviction failed' +} + +# bats test_tags=task:3 +test_recent_errors_last_two() { # @test + run bash log_analyzer.sh recent-errors "$BUSY_LOG" 2 + + assert_success + assert_output $'db query failed\ncache eviction failed' +} + +# bats test_tags=task:3 +test_recent_errors_more_than_there_are() { # @test + run bash log_analyzer.sh recent-errors "$BUSY_LOG" 10 + + assert_success + assert_output $'db connection lost\nweb timeout waiting for upstream\ndb query failed\ncache eviction failed' +} + +# bats test_tags=task:4 +test_alert_when_critical() { # @test + run bash log_analyzer.sh alert "$CRITICAL_LOG" + + assert_success + assert_output 'page the on-call engineer' +} + +# bats test_tags=task:4 +test_alert_when_only_errors() { # @test + run bash log_analyzer.sh alert "$BUSY_LOG" + + assert_success + assert_output '' +} + +# bats test_tags=task:4 +test_alert_when_quiet() { # @test + run bash log_analyzer.sh alert "$QUIET_LOG" + + assert_success + assert_output '' +} + +# bats test_tags=task:5 +test_check_with_errors() { # @test + run bash log_analyzer.sh check "$BUSY_LOG" + + assert_failure 1 + assert_output 'problems found' +} + +# bats test_tags=task:5 +test_check_with_critical() { # @test + run bash log_analyzer.sh check "$CRITICAL_LOG" + + assert_failure 1 + assert_output 'problems found' +} + +# bats test_tags=task:5 +test_check_when_quiet() { # @test + run bash log_analyzer.sh check "$QUIET_LOG" + + assert_success + assert_output '' +} diff --git a/exercises/concept/log-analyzer/log_analyzer.sh b/exercises/concept/log-analyzer/log_analyzer.sh new file mode 100644 index 00000000..2354307a --- /dev/null +++ b/exercises/concept/log-analyzer/log_analyzer.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash + +# This script helps you investigate the log file of a web service. +# +# The first argument names the task to perform. +# The remaining arguments are the data for that task. +# The first of those is always the name of the log file. +# +# Each line of the log file looks like this: +# +# 2024-03-01 08:00:05 ERROR db connection lost +# +# The fields are separated by spaces: the date, the time, the level, +# the name of the part of the service that wrote the entry, +# and then the words of the message. +# +# The `case` command below runs the code for the requested task. +# The `shift` command removes the first argument, so that "$1" is the first +# of the arguments that are left. +# +# Add your code below each task comment. +# Keep the other lines as they are. + +task=$1 +shift + +case $task in + error-sources) + # Task 1: print the name of each part of the service that logged an + # ERROR entry, one name per line, in alphabetical order, with no repeats. + # "$1" is the log file. + + ;; + + common-level) + # Task 2: print the level that is used by the most entries. + # "$1" is the log file. + + ;; + + recent-errors) + # Task 3: print the source and message of the last ERROR entries. + # "$1" is the log file, and "$2" is how many entries to print. + + ;; + + alert) + # Task 4: if the log file has any CRITICAL entry, print + # "page the on-call engineer". Otherwise, print nothing. + # In both cases, the script must exit with status 0. + # "$1" is the log file. + + ;; + + check) + # Task 5: if the log file has any ERROR or CRITICAL entry, print + # "problems found" and exit with status 1. + # Otherwise, print nothing and exit with status 0. + # "$1" is the log file. + + ;; +esac diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md index 31f1e8d2..4349c92c 100644 --- a/exercises/concept/road-map.md +++ b/exercises/concept/road-map.md @@ -13,7 +13,7 @@ Ref: [Syllabus][syllabus] | [arrays][arrays] | elyses-enchantments | | looping | | [more-arrays][more-arrays] | card-games | | arrays | | [associative-arrays][associative-arrays] | inventory-management | | arrays | -| [pipelines][pipelines] | | | quoting | +| [pipelines][pipelines] | log-analyzer | | quoting | | [functions][functions] | | | pipelines | | [redirection][redirection] | | | pipelines | | [heredocs][heredocs] | | | redirection |