# stern/stern architecture

> Architecture diagram of the GitHub repository stern/stern, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/stern/stern
- Repository: https://github.com/stern/stern

## Overview

##### Project Type and Purpose
- This is a Go-based command-line tool (“stern”) that tails logs from multiple Kubernetes pods and containers simultaneously.
- It acts as a client to the Kubernetes API server, watches for Pods, streams their logs, colorizes and formats them, and writes output to stdout or files.

##### High-Level File Structure
- `/cmd` directory: CLI entry-point code (flag parsing, help, completion, version, template support, config loading, command dispatch).
- `main.go`: Imports `cmd` and invokes the CLI.
- Dockerfile / Makefile / goreleaser.yaml: Build and release pipelines.
- `hack/`: Scripts to generate and verify documentation.
- Tests are co-located in both `cmd` and `stern` packages.

##### Key Architecture Components
a. CLI Frontend
- Component: “stern CLI”
- Responsibilities: parse flags & config, build query expressions, handle stdin or template inputs, initialize watcher and tailer modules.
b. Kubernetes API Client
- Component: “k8s API Server” (external service) and “client-go” integration layer
- Responsibilities: list/watch pods, fetch pod definitions, stream logs.
c. Pod & Container Watcher
- Component: “Watcher”
- Responsibilities: subscribe to Pod events, match resources against regex or `<resource>/<name>`, dispatch add/remove events.
d. Log Tailer
- Component: “LogStreamer” instances
- Responsibilities: concurrent `pods/log` streams per container, respecting `--tail`, `--no-follow`, `--max-log-requests`.
e. Container State Manager
- Component: “ContainerState”
- Responsibilities: track container lifecycle (running, waiting, terminated), filter by `--container-state`.
f. Formatter & Template Engine
- Component: “TemplateFormatter”
- Responsibilities: apply Go‐text templates or predefined outputs (raw, json, extjson), colorize fields using ANSI SGR codes, incorporate timestamp formatting.
g. Output
- Component: stdout / stderr (or piped consumer)
- Responsibilities: deliver final log lines to the user or other tools (e.g., `jq`).
h. Configuration
- Component: config file (`~/.config/stern/config.yaml`) or env vars

##### Relationships and Data Flows
1. User invokes `stern` CLI → flags & config are parsed by `cmd` module
2. `cmd` module constructs a “Query” object → passed to Watcher
3. Watcher uses client-go → subscribes to Pod list/watch from Kubernetes API
4. On pod add: Watcher spawns one or more LogStreamer per container via LogTailer
5. LogStreamer establishes a stream (`pods/log` API) → emits raw log lines
6. Raw lines pass through ContainerState filters → forwarded to TemplateFormatter
8. On pod/container termination: LogStreamer closes stream; Watcher cleans up resources

##### Architectural Patterns and Principles
- Modular layering: CLI layer (`cmd`) decoupled from core streaming logic (`stern` package)
- Concurrency: fan-out of per‐container log streams with limits (`--max-log-requests`)
- Observer pattern: Watcher reacting to Kubernetes Pod events
- Strategy pattern: pluggable output formats (default, raw, json, custom Go templates)

##### Technologies and Frameworks
- Go modules (go.mod)
- client-go (Kubernetes API client)
- text/template (for custom formatting)
- Docker (for containerized runs)
- GitHub Actions / GoReleaser (CI/CD pipelines)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% CLI Layer
    subgraph "CLI Layer"
        style CLI fill:#D0E8FF,stroke:#333,stroke-width:1px
        CLI["stern CLI"]
        Config["Configuration Loader"]
        Query["Query Constructor"]
    end

    %% Core Streaming Logic
    subgraph "Core Streaming Logic"
        style Watcher fill:#D0FFD6,stroke:#333,stroke-width:1px
        style K8sClient fill:#D0FFD6,stroke:#333,stroke-width:1px
        style LogStreamer fill:#D0FFD6,stroke:#333,stroke-width:1px
        style ContainerState fill:#D0FFD6,stroke:#333,stroke-width:1px
        Watcher["Watcher"]
        K8sClient["Kubernetes Client (client-go)"]
        LogStreamer["LogStreamer"]
        ContainerState["ContainerState"]
    end

    %% Formatter & Output
    subgraph "Formatting & Output"
        style TemplateFormatter fill:#FFE4B3,stroke:#333,stroke-width:1px
        style OutputWriter fill:#FFE4B3,stroke:#333,stroke-width:1px
        TemplateFormatter["TemplateFormatter"]
        OutputWriter["Output Writer"]
    end

    %% External Services
    K8sAPI["Kubernetes API Server"]:::external

    %% Connections
    CLI -->|"build Query object"| Query
    CLI -->|"initialize"| Watcher
    Query -->|"resource specs"| Watcher
    Watcher -->|"REST/HTTP watch & list"| K8sClient
    K8sClient -->|"pod events"| Watcher
    Watcher -->|"spawn per-container"| LogStreamer
    LogStreamer -->|"raw log lines (HTTP stream)"| ContainerState
    ContainerState -->|"filtered logs"| TemplateFormatter
    TemplateFormatter -->|"ANSI-encoded text"| OutputWriter
    OutputWriter -->|stdout/stderr| UserOutput["User / piped consumer"]

    %% External arrow
    Watcher -->|"REST/HTTP watch & list"| K8sAPI
    K8sAPI -->|"pod definitions & log stream"| K8sClient

    %% Click Events
    click CLI "https://github.com/stern/stern/blob/master/cmd/cmd.go"
    click CLI "https://github.com/stern/stern/blob/master/cmd/flag_version.go"
    click CLI "https://github.com/stern/stern/blob/master/cmd/flag_completion.go"
    click CLI "https://github.com/stern/stern/blob/master/cmd/helper.go"
    click Config "https://github.com/stern/stern/blob/master/stern/config.go"
    click Config "https://github.com/stern/stern/blob/master/cmd/helper.go"
    click Query "https://github.com/stern/stern/blob/master/stern/target.go"
    click Watcher "https://github.com/stern/stern/blob/master/stern/watch.go"
    click Watcher "https://github.com/stern/stern/blob/master/stern/resource_matcher.go"
    click K8sClient "https://github.com/stern/stern/blob/master/stern/list.go"
    click K8sClient "https://github.com/stern/stern/blob/master/stern/watch.go"
    click LogStreamer "https://github.com/stern/stern/blob/master/stern/tail.go"
    click LogStreamer "https://github.com/stern/stern/blob/master/stern/file_tail.go"
    click LogStreamer "https://github.com/stern/stern/blob/master/stern/tail_utils.go"
    click ContainerState "https://github.com/stern/stern/blob/master/stern/container_state.go"
    click TemplateFormatter "https://github.com/stern/stern/blob/master/stern/stern.go"
    click TemplateFormatter "https://github.com/stern/stern/blob/master/stern/color.go"
    click OutputWriter "https://github.com/stern/stern/blob/master/stern/stern.go"

    %% Styles
    classDef external fill:#EEEEEE,stroke:#666,stroke-width:1px,stroke-dasharray: 5 5
    class UserOutput external
```
