You need visibility into what’s going on across the stack—from the kernel to user-facing parts. Often, you get that visibility by knowing the right tool for the task.
This chapter is all about gathering and using different signals that Linux and its applications generate so that you can make informed decisions. For example, you’ll see how you can do the following:
-
Figure out how much memory a process consumes
-
Understand how soon you will run out of disk space
-
Get an alert on custom events for security reasons
To establish a common vocabulary, we’ll first review different signal types you might come across, such as system or application logs, metrics, and process traces. We’ll also have a look at how to go about troubleshooting and measuring performance. Next, we’ll focus on logs specifically, reviewing different options and semantics. Then, we’ll cover monitoring for different resource types, such as CPU cycles, memory, or I/O traffic. We’ll review different tools that you can use and show certain end-to-end setup you may wish to adopt.
You’ll learn that observability is often reactionary. That is, something crashes or runs slowly, and you start looking at processes and their CPU or memory usage, or dig into the logs. But there are also times when observability has more of an investigative nature—for example, when you want to figure out how long certain algorithms take. Last but not least, you can use predictive (rather than reactive) observability. For example, you can be alerted on a condition in the future, extrapolating the current behavior (disk usage for a predictable load is a good example where that might work well).
Likely the best visual overview on observability comes from performance maestro Brendan Gregg. Figure 8-1 , taken from his Linux Performance site , gives you a feeling for the wealth of moving parts and tooling available.
Figure 8-1. Linux observability overview. Credit : Brendan Gregg (shared under CC BY-SA 4.0 license)
Observability is an exciting topic with many use cases and lots of (open source) tooling available, so let’s first establish a strategy and look at some common terms used.
Basics
Before we get into the observability terminology, let’s step back a bit and look at how you turn the information provided into actionable insights and use it to fix an issue or optimize an app in a structured manner.
Observability Strategy
One widely established strategy in the observability context is the OODA loop (observe–orient–decide–act) . It offers a structured way to test a hypothesis based on observed data and act upon it—that is, a way to get actionable insights from signals.
For example, let’s say an application is slow. Let’s further assume there are multiple possible reasons for this (not enough memory, too few CPU cycles, network I/O insufficient, etc.). First, you want to be able to measure each resource consumption. Then you would change each resource allocation individually (keeping the others unchanged) and measure the outcome.
Does the performance improve after you provided more RAM to the app? If so, you may have found the reason. If not, you continue with a different resource, always measuring the consumption and trying to relate to the observed impact on the situation.
Terminology
There are a range of terms in the observability space, 1 and not all have formal definitions. In addition, the meanings might slightly differ if you’re looking at a single machine or are in a networked (distributed) setup:
Observability
Assessing the internal state of a system (such as Linux) by measuring external information, usually with the goal of acting upon it. For example, if you notice that your system reacts sluggishly, and measure how much main memory is available, you might find that a particular app hogs all the memory, and you may decide to terminate it to remedy the situation.
Signal types
Different ways to represent and emit information about the state of a system, either via symbolic means (payload is text, such as the case with logs) or numerical values (as with metrics) or combinations thereof. See also “Signal Types” .
Source
Generates signals, potentially of different types. Sources can be the Linux operating system or an application.
Destination
Where you consume, store, and further process signals. We call a destination that exposes a user interface (GUI, TUI, or CLI) a frontend . For example, a log viewer or a dashboard plotting time series is a frontend, whereas an S3 bucket is not (but can still act as a destination for, say, logs).
Telemetry
The process of extracting signals from sources and transporting (or routing, shipping) the signals to destinations, often employing agents that collect and/or preprocess signals (for example, filter or downsample).
Signal Types
Signals are how we communicate the state of a system for further processing or interpretation. By and large we distinguish between text payload (which is most suited for a human to search and interpret) and numerical payload (good for both machines and, in processed form, for humans). The three basic and common signal types relevant to our discussion in this chapter are: logs, metrics, and traces.
Logs
Logs are a fundamental signal type that every system, to some extent, generates. Logs are discrete events with a textual payload, meant for human consumption. Typically, these events are timestamped. Ideally, the logs are structured so that there is a clear meaning defined for each part of the log message. This meaning is potentially expressed through a formal schema so that validation can be automatically performed.
Interestingly, while every log has some structure (even if it’s not well defined and parsing is hard, potentially due to delimiter or edge cases), you will often hear the term structured logging . When people say that, they actually mean that the log is structured using JSON.
While automating log content is hard (given its textual nature), logs are still very useful for humans, and thus they will likely stay the dominating signal type for some time. We’ll dig deeper into handling logs in “Logging” . Logs are the most important signal type (for our considerations), and that’s why we’ll spend most of the time in this chapter dealing with them.
Metrics
Metrics are (usually regularly) sampled numerical data points, forming a time series. The individual data points can have additional context in the form of dimensions or identifying metadata. Normally, you don’t directly consume the raw metrics; instead, you use some sort of aggregation or graphical representation, or you get notified if a certain condition is met. Metrics can be useful both for operational tasks and for troubleshooting to answer questions like how many transactions an app completed or how long a certain operation took (in the past X minutes).
We distinguish between different types of metrics:
Counter
The value of a counter can only ever go up (besides resetting a counter to zero). An example of a counter metric is the total number of requests handled by a service or the bytes sent via an interface over a time period.
Gauges
A gauge value can go up or down. For example, you gauge the currently available overall main memory or the number of processes running.
Histograms
A sophisticated way to build a distribution of values. Using buckets, histograms allow you to assess how the data overall is structured. They also enable you to make flexible statements (such as 50% or 90% of the values fall into a certain range).
In “Monitoring” , we have a look at a range of tools that you can use for simple use cases, and in “Prometheus and Grafana” , you see an advanced example setup for metrics.
Traces
Traces are a dynamic collection of runtime information (for example, information about what syscalls a process uses, or the sequence of events in the kernel, for a given cause). Traces are often used not only for debugging but also for performance assessments. We have a look at this advanced topic in “Tracing and Profiling” .
Logging
As mentioned before, logs are (a collection of) discrete events with a textual payload, optimized for human consumption. Let’s decompose this statement to understand it better:
Discrete events
Think of a discrete event in the context of the codebase. You want to share information about what is going on in the code using an (atomic) log item. For example, you emit a log line that a database connection has been established successfully. Another log item might be to flag an error because a file is missing. Keep the scope of the log message small and specific, so it’s easier for someone consuming the message to find the respective location in the code.
Textual payload
The payload of a log message is of textual nature. The default consumers are humans. In other words, no matter if you’re using a log viewer on the command line, or a fancy log-processing system with visual UI, a human reads and interprets the content of the log message and decides on an action based on it.
From a structural perspective, overall, a log comprises the following:
A collection of log items, messages, or lines
Captures information about a discrete event.
Metadata or context
Can be present on a per-message basis as well as on a global scope (the entire log file, for example).
A format for how an individual log message is to be interpreted
Defines the log’s parts and meanings. Examples are line-oriented, space-separated messages or a JSON schema.
In Table 8-1 , you can see some common log formats. There are many (more-specific, narrower-scoped) formats and frameworks—for example, for database or programming languages.
Table 8-1. Common log formats | Format | Note | | --- | --- | | Common event format | Developed by ArcSight; used for devices, security use cases | | Common log format | For web servers; see also extended log format | | Graylog extended log format | Developed by Graylog; improves Syslog | | Syslog | For operating systems, apps, devices; see “Syslog” | | Embedded metric format | Developed by Amazon (both logs and metrics) |
As a good practice, you want to avoid overhead with logs (enabling fast lookups and a small footprint—that is, not taking up too much disk space). In this context, log rotation, for example, via logrotate , is used. An advanced concept called data temperature may also be useful, moving older log files to cheaper and slower storage (attached disk, S3 bucket, Glacier).
Warning
There’s one case where you need to be careful about logging information, especially in production environments. Whenever you decide to emit a log line in your app, ask yourself if you could potentially leak sensitive information. This sensitive information could be a password, an API key, or even simply user-identifying information (email, account ID).
The problem is that the logs are usually stored in a persistent form (say, on local disk or even in an S3 bucket). This means that even long after the process has terminated, someone could get access to the sensitive information and use it for an attack.
To signal the importance or intended target consumer of a log item, logs often define levels (for example DEBUG for development, INFO for normal status, or ERROR for unexpected situations that may require human intervention).
Now it’s time to get our hands dirty: let’s start with something simple and, as an overview, have a look at Linux’s central log directory (output shortened for readability):
$ ls -al /var/log
drwxrwxr-x 8 root syslog 4096 Jul 13 06:16 .
drwxr-xr-x 13 root root 4096 Jun 3 07:52 ..
drwxr-xr-x 2 root root 4096 Jul 12 11:38 apt/
-rw-r----- 1 syslog adm 7319 Jul 13 07:17 auth.log
-rw-rw---- 1 root utmp 1536 Sep 21 14:07 btmp
drwxr-xr-x 2 root root 4096 Sep 26 08:35 cups/
-rw-r--r-- 1 root root 28896 Sep 21 16:59 dpkg.log
-rw-r----- 1 root adm 51166 Jul 13 06:16 dmesg
drwxrwxr-x 2 root root 4096 Jan 24 2021 installer/
drwxr-sr-x+ 3 root systemd-journal 4096 Jan 24 2021 journal/
-rw-r----- 1 syslog adm 4437 Sep 26 13:30 kern.log
-rw-rw-r-- 1 root utmp 292584 Sep 21 15:01 lastlog
drwxr-xr-x 2 ntp ntp 4096 Aug 18 2020 ntpstats/
-rw-r----- 1 syslog adm 549081 Jul 13 07:57 syslog
Logs of the apt package manager
Logs of all login attempts (successful and failed) and authentication processes
Failed login attempts
Printing related logs
Logs of the dpkg package manager
Device driver logs; use dmesg to inspect
System install logs (when the Linux distro was originally installed)
The journalctl location; see “journalctl” for details
The kernel logs
All last logins of all users; use lastlog to inspect
NTP-related logs (see also “Network Time Protocol” )
The syslogd location; see “Syslog” for details
One common pattern for consuming logs live (that is, as it happens) is to follow logs ; that is, you watch the end of the log as new log lines are added (edited to fit):
$ tail -f /var/log/syslog
Sep 26 15:06:41 starlite nm-applet[31555]: ... 'GTK_IS_WIDGET (widget)' failed
Sep 26 15:06:41 starlite nm-dispatcher: ... new request (3 scripts)
Sep 26 15:06:41 starlite systemd[1]: Starting PackageKit Daemon...
Sep 26 15:06:41 starlite nm-dispatcher: ... start running ordered scripts...
Sep 26 15:06:42 starlite PackageKit: daemon start
^C
Follow the logs of the syslogd process with the -f option.
An example log line; see “Syslog” for the format.
Tip
If you want to see the log output of a process and at the same time store it in a file, you can use the tee command :
$ someprocess | tee -a some.log
Now you’d see the output of someprocess in your terminal, and the output would at the same time be stored in some.log . Note that we’re using the -a option to append to the log file, otherwise it would be truncated.
Let’s now have a look at the two most commonly used Linux logging systems.
Syslog
Syslog is a logging standard for a range of sources, from the kernel to daemons to user space. It has its roots in networked environments, and today the protocol comprises a textual format defined in RFC 5424 , along with deployment scenarios and security considerations. Figure 8-2 shows the high-level format of Syslog, but be aware that there are many seldom-used optional fields.
Figure 8-2. Syslog format as per RFC 5424
The Syslog format as defined in RFC 5424 has the following header fields (with TS and HN the most often used):
PRI
The message facility/severity
VER
The Syslog protocol number (usually left out since it can only be 1)
TS
Contains the time when the message was generated using ISO 8601 format
HN
Identifies the machine that sent the message
APP
Identifies the application (or a device) that sent the message
PID
Identifies the process that sent the message
MID
An optional message ID
The format also includes structured data , which is the payload in a structured (key/value-based) list where each element is bounded by [ ] .
Usually, one would use the syslogd binary to take care of the log management. Over time, other options have become available that you should be aware of:
An enhanced log daemon that you can use as a drop-in replacement for syslogd and that in addition supports TLS, content-based filtering, and logging into databases such as PostgreSQL and MongoDB. Available since late 1990.
Extends the Syslog protocol and can also be used with systemd . Available since 2004.
Despite its age, the Syslog family of protocols and tools is still around and widely available. With systemd becoming the de facto standard of init systems, used in every major Linux distro, there is, however, a new way to go about logging: meet the systemd journal.
journalctl
In “systemd” , we briefly touched upon a component that is part of the systemd ecosystem, responsible for log management: journalctl . In contrast to Syslog and the other systems we’ve used so far, journalctl uses a binary format to store the log items. This allows faster access and better storage footprints.
The binary storage format did attract some criticism when it was introduced since people are not able to continue to use the familiar tail , cat , and grep commands to view and search logs. Having said that, while one has to learn a new way to interact with logs when using journalctl , the learning curve is not too bad.
Let’s have a look at some common tasks. If you launch journalctl without parameters, it will present itself as an interactive pager (you can use the arrow keys or space bar to scroll through it and exit with q ) for all the logs.
To restrict the time range, you can, for example, use the following:
$ journalctl --since "3 hours ago"
$ journalctl --since "2021-09-26 15:30:00" --until "2021-09-26 18:30:00"
Restrict the time range to what happened in the past three hours.
Another way to restrict the time range, with explicit start and stop times.
You can limit the output to specific systemd units like so (assuming there is a service called abc.service ):
$ journalctl -u abc.service
Tip
The journalctl tool has a powerful way to format the output of the log items. Using the --output (or -o for short) parameter, you can optimize the output for a certain use case. Important values are the following:
cat
Short form, without time stamp or source
short
The default, emulating Syslog output
json
One JSON-formatted entry per line (for automation)
You can have the same experience to follow the logs as you’d have with tail -f using the following:
$ journalctl -f
Let’s put all the preceding information together into a concrete example. Assume you want to relaunch a security component of the Linux distro, managed by systemd : AppArmor . That is, in one terminal we restart the service using systemctl restart apparmor , and in another we execute the following command (output edited; the actual output is one log item per line):
$ journalctl -f -u apparmor.service
-- Logs begin at Sun 2021-01-24 14:36:30 GMT. --
Sep 26 17:10:02 starlite apparmor[13883]: All profile caches have been cleared,
but no profiles have been unloaded.
Sep 26 17:10:02 starlite apparmor[13883]: Unloading profiles will leave already
running processes permanently
...
Sep 26 17:10:02 starlite systemd[1]: Stopped AppArmor initialization.
Sep 26 17:10:02 starlite systemd[1]: Starting AppArmor initialization...
Sep 26 17:10:02 starlite apparmor[13904]: * Starting AppArmor profiles
Sep 26 17:10:03 starlite apparmor[13904]: Skipping profile in
/etc/apparmor.d/disable: usr.sbin.rsyslogd
Sep 26 17:10:09 starlite apparmor[13904]: ...done.
Sep 26 17:10:09 starlite systemd[1]: Started AppArmor initialization.
Follow the logs of the AppArmor service.
After systemd has stopped the service, here it comes back up again.
With that we are at the end of the logging section and move on to numerical values with metrics and the wider topic of monitoring.
Monitoring
Monitoring is the capturing of system and application metrics for a variety of reasons. For example, you may be interested in how long something takes or how many resources a process consumes (performance monitoring), or you may be troubleshooting an unhealthy system. The two types of activities you’ll carry out most often in the context of monitoring are as follows:
-
Tracking one or more metrics (over time)
-
Alerting on a condition
In this section, we first focus on some foundations and tools you should be aware of, and as we move further into the section, we get into more advanced techniques that may be relevant only in certain situations.
Let’s look at a simple example that displays some basic metrics, such as how long a system is running, memory usage, and more, using the uptime command :
$ uptime
08:48:29 up 21 days, 20:59, 1 user, load average: 0.76, 0.20, 0.09
Use the uptime command to display some basic system metrics.
Separated by commas, the output tells us how long the system is running, the number of users logged in, and then (in the load average section) three gauges: the 1-minute, 5-minute, and 15-minute average. These averages are the number of jobs in the run queue or waiting for disk I/O; the numbers are normalized and indicate how busy the CPUs are. For example, here the load average for the past 5 minutes was 0.2 (which in isolation doesn’t tell you much, so you have to compare it with the other values and track it over time).
Next, let’s monitor some basic memory utilization, using the free command (output compressed to fit):
$ free -h
total used free shared buff/cache available
Mem: 7.6G 1.3G 355M 395M 6.0G 5.6G
Swap: 975M 1.2M 974M
Show memory usage using a human-friendly output.
The memory stats: total/used/free/shared memory, memory used in buffers and used for caching (use -w if you don’t want the combined value), and the available memory.
The total/used/free amount of swap space—that is, physical memory moved out to a swap disk space.
A more sophisticated way to look at memory usage is using the vmstat (short for virtual memory stats) command . The following example uses vmstat in a self-updating manner (output edited to fit):
$ vmstat 1
procs -----------memory--------- ---swap-- ----io---- -system- -----cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
4 0 1184 482116 682388 5447048 0 0 12 105 28 191 6 3 91 0 0
0 0 1184 483444 682388 5446600 0 0 0 0 369 522 1 0 99 0 0
0 0 1184 483696 682392 5446600 0 0 0 104 278 374 1 1 99 0 0
^C
Show memory stats. The argument 1 means to print a new summary line every second.
Some important column headers: r is for the number of processes running or waiting for CPU (should be less than or equal to the number of CPUs you have), free is the free main memory in KB, in is the number of interrupts per second, cs is the number of context switches per second, and us to st are percentages of total CPU time across user space, kernel, idle, and the like.
To see how long a certain operation takes, you can use the time command:
$ time (ls -R /etc 2&> /dev/null)
real 0m0.022s
user 0m0.012s
sys 0m0.007s
Measure how long recursively listing all /etc subdirectories takes (we throw away all output, including errors, with 2&> /dev/null ).
The total (wall clock) time it took (not really useful other than for performance).
How long ls itself spent on-CPU (user space).
How long ls was waiting for Linux to do something (kernel space).
In the previous example, if you’re interested in how long an operation took, taking the sum of user and sys is a good approximation, and the ratio of the two gives you a good idea where it spends most of the execution time.
Now we focus on some more specific topics: network interfaces and block devices.
Device I/O and Network Interfaces
With iostat you can monitor I/O devices (output edited):
$ iostat -z --human
Linux 5.4.0-81-generic (starlite) 09/26/21 _x86_64_ (4 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
5.8% 0.0% 2.7% 0.1% 0.0% 91.4%
Device tps kB_read/s kB_wrtn/s kB_read kB_wrtn
loop0 0.00 0.0k 0.0k 343.0k 0.0k
loop1 0.00 0.0k 0.0k 2.8M 0.0k
...
sda 0.38 1.4k 12.4k 2.5G 22.5G
dm-0 0.72 1.3k 12.5k 2.4G 22.7G
...
loop12 0.00 0.0k 0.0k 1.5M 0.0k
Use iostat to show I/O device metrics. With -z , we tell it to show only devices where there was some activity, and the --human makes the output nicer (units are in human-readable form).
Example row: tps is the number of transfers (I/O requests) per second for that device, read is data volume, and wrtn is written data.
Next up: network interfaces with the ss command that can dump socket statistics (see also “Sockets” ). The following command lists both TCP and UDP sockets along with process IDs (output edited to fit):
$ ss -atup
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 0.0.0.0:60360 0.0.0.0:*
...
udp UNCONN 0 0 0.0.0.0:ipp 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:789 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:mdns 0.0.0.0:*
udp ESTAB 0 0 192.168.178.40:51008 74.125.193.113:443
...
tcp LISTEN 0 128 0.0.0.0:sunrpc 0.0.0.0:*
tcp LISTEN 0 128 127.0.0.53%lo:domain 0.0.0.0:*
tcp LISTEN 0 5 127.0.0.1:ipp 0.0.0.0:*
tcp LISTEN 0 4096 127.0.0.1:45313 0.0.0.0:*
tcp ESTAB 0 0 192.168.178.40:57628 74.125.193.188:5228
tcp LISTEN 0 128 [::]:sunrpc [::]:*
tcp LISTEN 0 5 [::1]:ipp [::]:*
Use ss with the following options: with -a , we select all (that is, both listening and nonlistening sockets); the -t and -u select TCP and UDP, respectively; and -p shows the processes using the sockets.
An example socket in use. It’s an established TCP connection between local IPv4 address 192.168.178.40 and remote 74.125.193.188 that seems idle: both data queued for receive ( Recv-Q ) and transmit ( Send-Q ) report zero.
Note
An outdated way to gather and display interface stats is using netstat . For example, if you want to have a continuously updated view on TCP and UDP, including process ID and using IP addresses rather than FQDNs, you could use netstat -ctulpn .
lsof stands for “list open files” and is a versatile tool with many use cases. The following example shows lsof used in the context of network connections (output edited to fit):
$ sudo lsof -i TCP:1-1024
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
...
rpcbind 26901 root 8u IPv4 615970 0t0 TCP *:sunrpc (LISTEN)
rpcbind 26901 root 11u IPv6 615973 0t0 TCP *:sunrpc (LISTEN)
List privileged TCP ports (needs root privileges).
Another usage example for lsof is a process-centric view: if you know the PID of a process (here, Chrome), you can use lsof to track file descriptors, I/O, etc. (output edited to fit):
$ lsof -p 5299
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
chrome 5299 mh9 cwd DIR 253,0 4096 6291458 /home/mh9
chrome 5299 mh9 rtd DIR 253,0 4096 2 /
chrome 5299 mh9 txt REG 253,0 179093936 3673554 /opt/google/chrome/chrome
...
There are many more tools for (performance) monitoring available—for example, sar (covering a range of counters, nice for scripts) and perf —some of which we will discuss in “Advanced Observability” .
Now that you have a handle on individual tools, let’s move on to integrated tools that allow you to interactively monitor Linux.
Integrated Performance Monitors
Using the tooling we discussed in the previous section, such as lsof or vmstat , is a good starting point and also useful in scripts. For more convenient monitoring, you may prefer integrated solutions. These typically come with a textual user interface (TUI), sometimes in color, and offer the following features:
-
Support for multiple resource types (CPU, RAM, I/O)
-
Interactive sorting and filtering (by process, user, resource)
-
Live updates and drill-down into details such as a process group or even cgroups and namespaces
For example, the widely available top provides an overview in the header—akin to what we saw in the uptime output—and then a tabular rendering of CPU and memory details, followed by a list of processes you can track (output edited):
top - 12:52:54 up 22 days, 1:04, 1 user, load average: 0.23, 0.26, 0.23
Tasks: 263 total, 1 running, 205 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.2 us, 0.4 sy, 0.0 ni, 99.3 id, 0.0 wa, 0.0 hi, 0.0 si, \
0.0 st%
KiB Mem : 7975928 total, 363608 free, 1360348 used, 6251972 buff/cache
KiB Swap: 999420 total, 998236 free, 1184 used. 5914992 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 20 0 225776 9580 6712 S 0.0 0.1 0:25.84 systemd
...
433 root 20 0 105908 1928 1700 S 0.0 0.0 0:00.05 `- lvmetad
...
775 root 20 0 36552 4240 3880 S 0.0 0.1 0:00.16 `- bluetoothd
789 syslog 20 0 263040 4384 3616 S 0.0 0.1 0:01.98 `- rsyslogd
Summary of system (compare with uptime output)
Task statistics
CPU usage statistics (user, kernel, etc.; similar to vmstat output)
The dynamic process list, including details on a per-process level; comparable to ps aux output
Tip
The following are the most important keys to remember in top :
?
To list the help (including key mappings)
V
To toggle to and from process tree view
m
To sort by memory usage
P
To sort by CPU consumption
k
To send a signal (like to kill )
q
To quit
While top is available in virtually any environment, there are a number of alternatives available, including the following:
htop ( Figure 8-3 )
An incremental top improvement that is faster than top and has a nicer user interface.
atop ( Figure 8-4 )
A powerful alternative to top . In addition to CPU and memory, it covers resources such as I/O and network stats in great detail.
A relatively new tool that is notable especially because it is cgroups v2–aware (see “Linux cgroups” ). Other tools do not understand cgroups and hence provide only a global resource view.
Figure 8-3. A screenshot of the htop tool
Figure 8-4. A screenshot of the atop tool
There are a number of other integrated monitoring tools available that go beyond the basic sources or that specialize in certain use cases. These include but are not limited to the following:
A powerful hybrid that covers devices in addition to the usual resources
An integrated performance analyzer that allows you to display and graph a range of metrics
For network traffic monitoring; an ss replacement that offers a nice TUI
For network traffic monitoring; a more powerful alternative to traceroute (see “Routing” for details on traceroute )
Now that you have a broad understanding of the tooling to consume system metrics, let’s see how you can expose those from your own code.
Instrumentation
So far we’ve focused on signals coming from the kernel or existing applications (that is, code that you don’t own). Now we move to the topic of how you can, similar to logs, equip your code to emit metrics.
The process of inserting code to emit signals, especially metrics, is mainly relevant if you’re developing software. This process is usually referred to as instrumentation , and there are two common instrumentation strategies: autoinstrumentation (no additional effort for you as a developer) and custom instrumentation , where you manually insert code snippets to, for example, emit a metric at a certain point in your code base.
You can use StatsD , with client-side libraries available for a number of programming languages, such as Ruby , Node.js , Python , and Go . StatsD is nice, but it has a few limitations, especially in dynamic environments such as Kubernetes or IoT. In those environments, a different approach—sometimes called pull-based or scraping —is usually a better choice. With scraping, applications expose metrics (usually via an HTTP endpoint), and an agent then calls this endpoint to retrieve metrics, rather than configuring the app with where to send the metrics to. We’ll return to this topic in “Prometheus and Grafana” .
Advanced Observability
Now that you know the basics of Linux observability, let’s have a look at some more advanced topics in this space.
Tracing and Profiling
The term tracing is overloaded: in the context of Linux, on a single machine, tracing means capturing the process execution (function calls in user space, syscalls, etc.) over time.
Note
In a distributed setup like containerized microservices in Kubernetes or a bunch of Lambda functions that are part of a serverless app, we sometimes shorten distributed tracing (for example, with OpenTelemetry and Jaeger) to tracing . This type of tracing is out of scope for this book.
There are a number of data sources in the context of a single Linux machine. You can use the following as sources for tracing:
The Linux kernel
Traces can come from functions in the kernel or be triggered by syscalls. Examples include kernel probes (kprobes) or kernel tracepoints .
User space
Application function calls, for example via user space probes (uprobes) , can act as a source for traces.
Use cases for tracing include the following:
-
Debugging a program using, for example, the
stracetracing tool -
Performance analysis with a frontend, using
perf
Warning
You may be tempted to use strace everywhere; however, you should be aware of the overhead it causes. This is particularly relevant for production environments. Read “strace Wow Much Syscall” by Brendan Gregg to understand the background.
See Figure 8-5 for an example output of sudo perf top , which generates a summary by process.
Figure 8-5. A screenshot of the perf tracing tool
Going forward, it seems that eBPF (see “A Modern Way to Extend the Kernel: eBPF” ) will become the de facto standard to implement tracing, especially for custom cases. It has a rich ecosystem and growing vendor support, so if you’re looking for a future-proof tracing method, make sure it’s using eBPF.
One particular use case for tracing is profiling —that is, to identify frequently called code sections. Some relevant low-level tooling for profiling include pprof , Valgrind , and flame graph visualizations .
There are many options to consume perf output interactively and visualize traces; for example, see Mark Hansen’s blog post “Linux perf Profiler UIs” .
Continuous profiling is an advanced variant of profiling, which captures traces (kernel and user space) over time. Once these timestamped traces are collected, you can plot and compare them and drill down into interesting segments. One very promising example is the eBPF-based open source project parca , shown in Figure 8-6 .
Figure 8-6. A screenshot of parca, a continuous profiling tool
Prometheus and Grafana
If you’re dealing with metrics over time (time series data), using the Prometheus and Grafana combo is something you may want to consider for advanced observability.
I’ll show you a simple, single-machine setup that you can use to dashboard and even alert on things going on in your Linux machine.
We’ll use the node exporter to expose a range of system metrics, from CPU to memory and network. We’ll then use Prometheus to scrape the node exporter. Scraping means that Prometheus calls an HTTP endpoint that the node exporter offers via the URL path /metrics , returning the metrics in OpenMetrics format . For that to happen, we need to configure Prometheus with the URL of the node exporter’s HTTP endpoint. The final step in our setup is using Prometheus as a datasource in Grafana, where you can see the time series data (metrics over time) in dashboards and can even alert on certain conditions, such as low disk space or CPUs overloading.
So, as a first step, download and untar the node exporter, and have it run the binary with ./node_exporter & in the background. You can check if it’s running properly with the following (output edited):
$ curl localhost:9100/metrics
...
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 7.2575e-05
go_gc_duration_seconds{quantile="0.25"} 0.00011246
go_gc_duration_seconds{quantile="0.5"} 0.000227351
go_gc_duration_seconds{quantile="0.75"} 0.000336613
go_gc_duration_seconds{quantile="1"} 0.002659194
go_gc_duration_seconds_sum 0.126529838
go_gc_duration_seconds_count 390
...
Now that we have the signal data source set up, we run both Prometheus and Grafana as containers. For the following, you’ll need Docker (see “Docker” ) installed and configured.
Create a Prometheus configuration file called prometheus.yml with the following content:
global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
monitor: 'mymachine'
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'machine'
static_configs:
- targets: ['172.17.0.1:9100']
Prometheus itself exposes metrics, so we include this (self-monitoring).
That’s our node exporter. Since we’re running Prometheus in Docker, we can’t use localhost but rather use the IP address Docker uses by default.
We use the Prometheus configuration file we created in the previous step and mount it into the container via a volume, like so:
$ docker run --name prometheus \
--rm -d -p 9090:9090 \
-v /home/mh9/lml/o11y/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus:main
The parameters here make Docker remove the container on exit ( --rm ), run as a daemon ( -d ), and expose the port 9090 ( -p ) so we can use it from our machine.
Mapping our config file as a volume into the container. Note that here you will have to replace /home/mh9/lml/o11y/ with the path where you stored it. Also, this has to be an absolute path. So, if you want to keep this flexible, you could use $PWD in bash or (pwd) in Fish rather than the hardcoded path.
After you’ve executed the previous command, open localhost:9000 in your browser, then click Targets in the Status dropdown menu at the top. You should, after a few seconds, see something like the screen shown in Figure 8-7 , confirming that Prometheus has successfully scraped metrics from itself and the node exporter.
Figure 8-7. A screenshot of Prometheus targets in the Web UI
Next, we launch Grafana:
$ docker run --name grafana \
--rm -d -p 3000:3000 \
grafana/grafana:8.0.3
After you’ve executed the preceding command, open localhost:3000 in your browser and use admin for both the username and password. Next, we need to do two things:
-
Add Prometheus as a datasource in Grafana, using
172.17.0.1:9100as the URL -
Import the Node Exporter Full dashboard
Once you’ve done this, you should see something akin to Figure 8-8 .
Figure 8-8. A screenshot of the Grafana UI with the Node Exporter Full dashboard
That was some exciting advanced observability for Linux, using modern tooling. Given that the Prometheus/Grafana setup is more elaborate and has a number of moving parts, you’ll likely not use it for a trivial task. In other words, the Linux native tooling we discussed in this section should go a long way; however, there are more advanced use cases—for example, home automation or a media server—where you want to have a more complete solution, in which case Prometheus/Grafana makes a lot of sense .
Conclusion
In this chapter, we looked at making sure you’re not flying blind when you’re running into issues with your Linux system. The main signal types you’d typically use for diagnostics are logs (textual) and metrics (numerical). For advanced cases, you can apply profiling techniques, rendering resource usage of processes along with the execution context (source file and lines of the source code that is being executed).
If you want to learn more and dive deeper into this topic, have a look at these resources:
Basics
-
Systems Performance: Enterprise and the Cloud , second edition , by Brendan Gregg (Addison-Wesley)
Logging
Monitoring
Advanced
Having completed this chapter and those that preceded it, you now know the basics of Linux, from kernel to shell to filesystems and networking. The last chapter of this book is a collection of advanced topics that didn’t quite fit in other chapters. You may find them interesting and useful, depending on your goals, but for most day-to-day tasks, you now know everything you need to get by.
1 Observability is also sometimes referred to with the numeronym o11y , as there are 11 letters between the o and the y .