Lesson 1: Linux Primitives, File Descriptors, systemd & Bash Automation
๐ง The Concept (Explain Like Iโm 5)
Think of an operating system like a massive corporate headquarters:
- The Hardware: The physical building, electricity, and filing cabinets (CPU, RAM, Disks, Network Interface Cards).
- The Kernel: The executive facilities manager who holds the master keys to every room, regulates the power, and decides which department gets desk space. Nobody touches the hardware directly; you must submit a formal requisition (System Call / Syscall).
- The Shell (Bash): The receptionist at the front desk. When you type
cat report.txt, you hand a written note to the receptionist. The receptionist translates your note into an intercom message to the facilities manager (sys_open,sys_read), who pulls the folder from the file cabinet (Disk) and hands it back. - File Descriptors (FDs): The three standard mailboxes on every workerโs desk:
- FD 0 (
stdin): Inbound conveyor belt (keyboard input or data piped from another tool). - FD 1 (
stdout): Outbound conveyor belt (normal reports to your screen or a log file). - FD 2 (
stderr): The emergency red chute (urgent error alerts, separated so they donโt corrupt clean data).
- FD 0 (
- systemd (PID 1): The automated 24/7 night-shift supervisor. If an employee collapses from exhaustion, systemd restarts them immediately, logs the incident, and ensures core services never go offline.
๐ข The Enterprise Context (Why Platform Architects Care)
- Containers Are Just Linux Processes: There is no such thing as a โDocker containerโ inside the Linux kernel. A container is simply an isolated Linux process running on an EC2 instance or bare-metal host, wrapped in kernel namespaces and cgroups. If you cannot debug Linux file descriptors, memory leaks, zombie processes, and signal handling, you cannot troubleshoot Kubernetes pods.
- Production Bootstrap Reliability: Cloud-init bootstrap scripts, CI/CD deployment pipelines, and container entrypoints (
entrypoint.sh) are written in Bash. A poorly written script that fails silently or ignores error codes can boot a half-configured VM into an Auto Scaling Group, routing production customer traffic to a dead instance. - Node-Level Daemons: Platform engineers configure and maintain
systemdunit files on every cluster node for foundational services:kubelet,containerd, Cilium CNI, node-problem-detector, and Datadog/Prometheus exporters.
๐บ๏ธ Visual Architecture: Linux Kernel, File Descriptors & Process Tree
flowchart TD
User["๐จโ๐ป Terminal / Engineer"] -->|"Types Command"| Shell["๐ The Shell (Bash / Zsh)"]
subgraph Streams ["Standard I/O Streams (File Descriptors)"]
FD0["<b>FD 0 (stdin)</b>: Input Stream / Pipe"]
FD1["<b>FD 1 (stdout)</b>: Standard Output Stream"]
FD2["<b>FD 2 (stderr)</b>: Standard Error Stream"]
end
Shell --> FD0
Shell --> FD1
Shell --> FD2
Shell -->|"Syscalls: fork + execve"| Kernel["<b>Linux Kernel Core</b><br/>(Scheduler, Memory Manager, VFS, Network Stack)"]
subgraph ProcTree ["systemd Process Hierarchy (PID 1)"]
PID1["<b>systemd (PID 1)</b><br/>Parent of all userspace processes & Orphan Reaper"]
Kubelet["kubelet.service (PID 1042)"]
Containerd["containerd.service (PID 1105)"]
AppProc["containerd-shim -> app (PID 2450)"]
PID1 --> Kubelet
PID1 --> Containerd
Containerd --> AppProc
end
Kernel --> PID1
Kernel --> Hardware[("Physical Hardware: CPU, RAM, NVMe, NIC")]
๐ฌ Under the Hood: The Linux Process Lifecycle & Signals
Every process in Linux is spawned through two foundational system calls:
fork(): Clones the parent process, creating an identical child process with a new Process ID (PID) and Copy-On-Write (COW) memory pages.execve(): Overwrites the child processโs memory space with a new executable program (e.g., launching NGINX or Python).
stateDiagram-v2
[*] --> Created: fork()
Created --> Running: execve() / Scheduled by CPU
Running --> InterruptibleSleep: Waiting for Event (S)
Running --> UninterruptibleSleep: Waiting for Disk / Hardware I/O (D)
InterruptibleSleep --> Running: Signal received / Event complete
UninterruptibleSleep --> Running: I/O Hardware read complete
Running --> Stopped: SIGSTOP / SIGTSTP (T)
Stopped --> Running: SIGCONT
Running --> Zombie: exit() / Terminated (Z)
Zombie --> [*]: Parent calls waitpid() to read exit code
Process States Decoded (ps aux / top)
R(Running / Runnable): Process is actively executing on a CPU core or sitting in the kernel run queue waiting for its time slice.S(Interruptible Sleep): Waiting for an event or network socket (e.g., NGINX waiting for an incoming HTTP request). Can be awakened immediately by signals likeSIGTERM.D(Uninterruptible Sleep): Waiting directly on hardware device drivers (usually disk I/O or an unresponsive NFS/EBS network mount). Cannot be killed by any signal, includingkill -9! If processes accumulate inDstate, host load average spikes even if CPU usage is 0%.Z(Zombie / Defunct): The process has finished executing and calledexit(), but its parent has not yet executedwait()orwaitpid()to collect its exit status. A zombie consumes no CPU or RAM, but it retains a slot in the kernel PID table.T(Stopped): Suspended by a signal (e.g., pressingCtrl+ZsendsSIGTSTP).
Essential POSIX Signals
Signals are asynchronous notifications sent by the kernel or userspace to notify a process of an event:
| Signal Name | Number | Default Action | Catchable? | Enterprise Platform Significance |
|---|---|---|---|---|
SIGHUP |
1 |
Terminate | Yes | Configuration reload. Tells NGINX/Prometheus to re-read configs without dropping connections. |
SIGINT |
2 |
Terminate | Yes | Interactive interrupt generated by Ctrl+C in terminal. |
SIGKILL |
9 |
Force Kill | NO | Unconditional termination by the kernel. Cannot be intercepted, handled, or ignored. Causes dirty state/data corruption if used improperly. |
SIGTERM |
15 |
Terminate | Yes | Standard graceful termination request sent by Kubernetes and systemd. Apps catch this, stop accepting new requests, drain active sockets, and flush caches. |
SIGCHLD |
17 |
Ignore | Yes | Sent to parent process when a child terminates, signaling parent to invoke waitpid(). |
In a standard Linux VM, systemd runs as PID 1 and automatically acts as the subreaperโit adopts orphaned child processes and reaps their exit codes.
Inside a Docker container, your application process (e.g., node or python) frequently runs as PID 1. If your application spawns child processes (e.g., database shell queries or image processing forks) and fails to catch SIGCHLD, those processes become permanent zombies. Over time, they exhaust the Linux kernel PID table (/proc/sys/kernel/pid_max), causing the entire host node to fail with fork: Cannot allocate memory. Always use a lightweight init reaper like tini or Dockerโs --init flag.
๐๏ธ Linux Virtual Filesystem: Inspecting /proc
The /proc directory is not a physical directory on a hard drive; it is a pseudo-filesystem (procfs) created dynamically in memory by the Linux kernel. It exposes live kernel data structures as human-readable text files:
# 1. Inspect command line parameters of a running process
cat /proc/1042/cmdline | tr '\0' ' '
# 2. View process status, memory consumption, and thread count
cat /proc/1042/status | grep -E "Name|VmRSS|Threads"
# 3. List all file descriptors currently opened by a process
ls -l /proc/1042/fd/
# Output:
# lrwx------ 1 root root 64 Oct 12 10:00 0 -> /dev/null
# l-wx------ 1 root root 64 Oct 12 10:00 1 -> /var/log/app.log
# lrwx------ 1 root root 64 Oct 12 10:00 3 -> socket:[28911] # Live network socket!
# 4. Count total open file descriptors across the entire OS vs the kernel limit
cat /proc/sys/fs/file-nr
# Output: 1472 0 1048576 (Allocated FDs, Free FDs, Maximum Allowed)
๐งฎ Permissions & The Security Grid
Every file and directory in Linux has an ownership and permission grid consisting of 10 characters:
- r w x r - x r - -
^ \___/ \___/ \___/
| | | |
| | | +--> Other / World Permissions (Read only)
| | +---------> Group Permissions (Read and Execute)
| +----------------> Owner Permissions (Read, Write, Execute)
+---------------------> File Type: '-' = File, 'd' = Directory, 'l' = Symlink, 's' = Socket
Binary to Octal Conversion Table
Each triplet is calculated using 3 binary bits: Value = (Read ร 4) + (Write ร 2) + (Execute ร 1):
| Octal | Binary | Permissions | Typical Enterprise Usage |
|---|---|---|---|
| 7 | 111 |
rwx |
Owner of an executable automation script or directory |
| 6 | 110 |
rw- |
Standard configuration files (Read & Write, no Execute) |
| 5 | 101 |
r-x |
Directories (Execute bit is mandatory to cd into a directory) |
| 4 | 100 |
r-- |
Read-only secrets, TLS certificates, or license keys |
| 0 | 000 |
--- |
Completely blocked from group/others |
Special Permission Bits: SUID, SGID & Sticky Bit
- SUID (Set Owner User ID,
4000): File executes with the permissions of the file owner rather than the user running it (e.g.,/usr/bin/passwdallows standard users to write to/etc/shadow). - SGID (Set Group ID,
2000): Newly created files inherit the parent directoryโs group instead of the userโs primary group. Essential for shared team deployment directories. - Sticky Bit (
1000): Prevents users from deleting or renaming files owned by others within a shared directory (e.g.,/tmphas permissions1777).
# Secure configuration file: Owner read/write, Group read, Others denied
chmod 640 /etc/app/database.conf
# Give team shared directory SGID so all created files belong to 'platform' group
chmod 2775 /opt/platform/shared
# Ensure /tmp maintains sticky bit protection
chmod 1777 /tmp
๐ File Descriptors & Advanced Redirection Mastery
# 1. Redirect standard output (FD 1) to a file (overwrites)
echo "Pipeline phase 1 complete" > deploy.log
# 2. Append standard output (FD 1) to an existing file
echo "Pipeline phase 2 complete" >> deploy.log
# 3. Redirect ONLY errors (FD 2) to an error log
./db_migrate.sh 2> errors.log
# 4. Redirect BOTH stdout and stderr to the same file
./run_tests.sh > full_output.log 2>&1
# Modern Bash alternative:
./run_tests.sh &> full_output.log
# 5. Black-hole output (Discard both stdout and stderr completely)
curl -s https://internal.healthz > /dev/null 2>&1
# 6. Here-Document: Write multi-line files declaratively in automation scripts
cat << 'EOF' > /etc/docker/daemon.json
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
}
}
EOF
# 7. tee: Write output to both the terminal screen and a file simultaneously
echo "Config updated" | sudo tee -a /var/log/provision.log
โ๏ธ systemd Unit File Architecture
Enterprise platform engineers write and manage systemd units to control node-level agents. Below is a production unit file with strict sandboxing and resource limits:
# /etc/systemd/system/node-health-checker.service
[Unit]
Description=Enterprise Node Health Check Daemon
Documentation=https://docs.corp.internal/platform/node-health
After=network.target containerd.service
Wants=containerd.service
[Service]
Type=simple
User=platform-agent
Group=platform-agent
WorkingDirectory=/opt/platform/health-agent
ExecStart=/usr/local/bin/python3 /opt/platform/health-agent/main.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=5s
# Environment configuration
Environment=LOG_LEVEL=info
EnvironmentFile=/etc/default/node-health
# Kernel Sandboxing & Security Controls
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/log/node-health
# Resource Quotas (Prevent noisy neighbor memory exhaustion)
MemoryMax=512M
MemoryHigh=400M
CPUQuota=50%
[Install]
WantedBy=multi-user.target
# Reload systemd manager after editing unit files
sudo systemctl daemon-reload
# Enable service to automatically start upon VM boot
sudo systemctl enable node-health-checker.service
# Start the service immediately
sudo systemctl start node-health-checker.service
# Inspect service logs in real time using journalctl with priority filtering
journalctl -u node-health-checker.service -f -p err --since "1 hour ago"
๐ Text Manipulation: grep, sed & awk Mastery
In incident response situations, platform engineers parse millions of log lines using shell tools:
# 1. grep: Extract matching lines recursively with context lines
# -r: recursive, -i: case-insensitive, -n: line numbers, -C 2: 2 lines before & after
grep -rin -C 2 "connection reset by peer" /var/log/nginx/
# 2. sed: Stream Editor - In-place substitution across configuration files
# Replaces 'LOG_LEVEL=debug' with 'LOG_LEVEL=warn' across all environment files
sed -i 's/LOG_LEVEL=debug/LOG_LEVEL=warn/g' /etc/environment.d/*.conf
# 3. awk: Powerful column processing and tabular analysis
# Calculate total memory consumed by all 'node' processes:
ps aux | grep "[n]ode" | awk '{sum += $6} END {printf "Total RAM: %.2f MB\n", sum/1024}'
# 4. Extract top 5 client IP addresses causing HTTP 500 errors from NGINX access log:
awk '$9 ~ /^5/ {print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -n 5
๐ Enterprise Production Bash Scripting Template
Never write raw, brittle Bash scripts. Always implement the Strict Mode pattern with traps and structured logging:
#!/usr/bin/env bash
# ==============================================================================
# Enterprise Node Provisioning Script
# ==============================================================================
# -e: Exit immediately if any command exits with a non-zero status
# -u: Treat unset variables as an error and exit immediately
# -o pipefail: Pipeline exit status is that of the last command that returned non-zero
set -euo pipefail
readonly LOG_FILE="/var/log/provision.log"
readonly ENVIRONMENT="${1:-production}" # Default to 'production' if $1 is omitted
log() {
local level="$1"
local message="$2"
local timestamp
timestamp="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
echo "[${timestamp}] [${level}] ${message}" | tee -a "${LOG_FILE}"
}
cleanup() {
local exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then
log "ERROR" "Provisioning failed with exit code ${exit_code}! Performing rollback..."
else
log "INFO" "Execution completed successfully. Cleaning temporary files."
fi
rm -f /tmp/bootstrap_token_*
}
trap cleanup EXIT ERR INT TERM
log "INFO" "Starting node provisioning for environment: ${ENVIRONMENT}..."
# Verify script is executed with root privileges
if [[ $EUID -ne 0 ]]; then
log "ERROR" "This script must be executed as root (use sudo)."
exit 1
fi
# Example conditional check
if ! command -v containerd &> /dev/null; then
log "WARN" "containerd not detected. Installing dependencies..."
# Installation commands execute here
else
log "INFO" "containerd is already installed. Version: $(containerd --version | awk '{print $3}')"
fi
log "INFO" "Bootstrap sequence completed without errors."
exit 0
โ ๏ธ Real-World Failure Modes & Troubleshooting Playbook
Scenario 1: Load Average is 40, but CPU Usage is 2%
- Symptom: CloudWatch or Datadog alerts on high Node Load Average (
loadavg > 30), buttopreports CPU usage is nearly idle (%Cpu(s): 1.5 us, 0.5 sy, 98.0 id). - Root Cause: Load Average in Linux measures processes in both
R(Running) andD(Uninterruptible Sleep) states. Processes inDstate are stuck waiting on an unresponsive storage subsystem (e.g., an AWS EBS volume experiencing an IOPS throttling event or a locked NFS mount). - Triage Command:
# Find all processes stuck in Uninterruptible Sleep (D state) ps aux | awk '$8 ~ /D/ {print $2, $8, $11}' # Inspect what kernel system call the stuck process is blocked on cat /proc/<PID>/stack
Scenario 2: โjava: error while loading shared libraries: cannot open โฆ: Too many open filesโ
- Symptom: Microservices fail to accept new TCP connections or read configuration files with
errno 24: EMFILE (Too many open files). - Root Cause: The process has exceeded its configured file descriptor limit (
ulimit -n). By default, many Linux distros default to 1,024 open files per process. - Triage & Remediation:
# Check current soft and hard limits for the running shell ulimit -Sn # Soft limit ulimit -Hn # Hard limit # Count file descriptors currently open for the specific process ls -1 /proc/<PID>/fd | wc -l # Increase limit permanently in /etc/security/limits.conf # * soft nofile 65535 # * hard nofile 65535 # For systemd managed services, set in the unit file: # LimitNOFILE=65535
๐ Staff Architect & SRE Interview Scenarios
โ Question 1: The Difference Between Load Average in Linux vs UNIX
Question: Why does Linux include processes in D state (Uninterruptible Sleep) in its Load Average calculation, whereas traditional UNIX systems (like BSD) only count R (Runnable) processes? What architectural implication does this have for monitoring?
Answer: Traditional UNIX systems only measure CPU demand (how many processes want the CPU right now). Linux creator Linus Torvalds deliberately chose to also include processes in D state because waiting on disk or network storage is also a demand on system capacity. If a database is stalled waiting for NVMe writes, the system is just as overloaded as if the CPU were pinned at 100%. For platform architects, this means a high Load Average on Linux indicates either CPU exhaustion OR storage/I/O bottlenecks.
โ Question 2: Why `kill -9` Can Break Production Applications
Question: Why do senior SREs prohibit junior engineers from immediately running kill -9 (SIGKILL) on misbehaving production database or message broker processes?
Answer: SIGKILL (Signal 9) cannot be caught or handled by the target process; the Linux kernel immediately frees the processโs memory pages and destroys its PID without notifying the application. This prevents the application from executing its cleanup handlers: in-flight database transactions are not rolled back, WAL logs are left partially written, active socket connections to clients are abruptly terminated with TCP RST instead of FIN, and inter-process lock files (like .pid or advisory file locks) remain orphaned on disk, preventing the service from restarting cleanly. Always issue SIGTERM (Signal 15) first and allow the grace period to expire before resorting to SIGKILL.