Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
49 changes: 49 additions & 0 deletions exercises/concept/log-analyzer/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -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
89 changes: 89 additions & 0 deletions exercises/concept/log-analyzer/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -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
```
200 changes: 200 additions & 0 deletions exercises/concept/log-analyzer/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -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
```
3 changes: 3 additions & 0 deletions exercises/concept/log-analyzer/.docs/introduction.md.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Introduction

%{concept:pipelines}
20 changes: 20 additions & 0 deletions exercises/concept/log-analyzer/.meta/config.json
Original file line number Diff line number Diff line change
@@ -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."
}
Loading