monitor

package
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 14 Imported by: 0

README

Monitor Middleware

Mount this middleware on two endpoints and it reports what the process and the machine are doing right now: CPU and memory of the process, CPU, RAM and load average of the host, open connections and uptime. One endpoint answers JSON, the other serves a small self-refreshing HTML dashboard that reads it.

The metrics are also published through the standard expvar package (pid_cpu, pid_ram, pid_conns, os_cpu, os_ram, os_total_ram, os_load_avg, os_conns), so any collector that already reads /debug/vars picks them up.

Installation

To use the monitor middleware, you need to import it in your Iris application:

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/monitor"
)

Usage

monitor.New(monitor.Options) returns a *monitor.Monitor rather than a single handler, because it exposes two of them and owns the background sampler that both read:

  • m.Stats writes the statistics as JSON.
  • m.View renders the HTML dashboard, which polls Stats.

Call m.Stop() when the monitor is no longer needed, to end the sampler.

package main

import (
    "os"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/basicauth"
    "github.com/kataras/iris/v14/middleware/monitor"
)

func main() {
    app := iris.New()

    m := monitor.New(monitor.Options{
        ViewTitle: "My Application",
    })
    defer m.Stop()

    // SECURITY: the stats endpoint must NOT be public, see below.
    auth := basicauth.Default(map[string]string{
        "admin": os.Getenv("MONITOR_PASSWORD"),
    })

    app.Get("/monitor", auth, m.View)
    app.Get("/monitor/stats", auth, m.Stats)

    app.Listen(":8080")
}

Options

The zero value is valid; every field below is optional.

  • PID: the process to watch. Defaults to the current one.
  • RefreshInterval: how often the statistics are sampled. Defaults to 2 seconds.
  • ViewRefreshInterval: how often the dashboard re-fetches them. Defaults to RefreshInterval.
  • ViewAnimationInterval: when greater than zero, animates the dashboard's lines. Defaults to zero, no animation.
  • ViewTitle: the title of the dashboard document. Defaults to empty.

Security

The stats endpoints must not be public. They report the process id, resident memory, host CPU and RAM, load average and connection counts: a precise picture of the machine, useful to anyone deciding whether and when to attack it. Guard them exactly as you would pprof, with authentication, a private listener or an internal-only route, as the example above does.

Note also that importing this package registers its metrics into the default expvar map at init, so they are visible through any mounted /debug/vars handler too.

Documentation

Overview

Package monitor reports live process and system statistics (CPU, memory, goroutines, uptime) as JSON and as a small HTML dashboard.

Its entry point is New(Options), which returns a *Monitor rather than a Handler because it exposes two of them - `Stats` for the JSON payload and `View` for the dashboard page - and owns the background sampler that both read; call `Stop` when it is no longer needed.

Index

Constants

View Source
const DefaultRefreshInterval = 2 * time.Second

DefaultRefreshInterval is the stats refresh interval used when Options.RefreshInterval is not set.

Variables

This section is empty.

Functions

This section is empty.

Types

type Monitor

type Monitor struct {
	Holder *StatsHolder
	// contains filtered or unexported fields
}

Monitor tracks and renders the server's process and operating system statistics.

Look its `Stats` and `View` methods. Initialize with the `New` package-level function.

func New

func New(opts Options) *Monitor

New returns a new Monitor. Metrics stored through expvar standard package: - pid_cpu - pid_ram - pid_conns - os_cpu - os_ram - os_total_ram - os_load_avg - os_conns

Check https://github.com/iris-contrib/middleware/tree/master/expmetric which can be integrated with datadog or other platforms.

SECURITY WARNING: the stats endpoint MUST NOT be public.

It reports the process id, resident memory, host CPU and RAM, load average and connection counts - a precise picture of the machine, useful to anyone deciding whether and when to attack it. Guard it exactly like pprof:

auth := basicauth.Default(map[string]string{"admin": os.Getenv("MONITOR_PASSWORD")})
app.Get("/monitor", auth, m.View)
app.Get("/monitor/stats", auth, m.Stats)

Note also that importing this package registers its metrics into the default expvar map at init, so they are also visible through any mounted "/debug/vars" handler.

func (*Monitor) Stats

func (m *Monitor) Stats(ctx *context.Context)

Stats sends the stats as json.

func (*Monitor) Stop

func (m *Monitor) Stop()

Stop terminates the retrieve stats loop for the process and the operating system statistics. No other monitor instance should be initialized after the first Stop call.

func (*Monitor) View

func (m *Monitor) View(ctx *context.Context)

View renders a default view for the stats.

type Options

type Options struct {
	// Optional process id, defaults to the current one.
	PID int32 `json:"pid" yaml:"PID"`

	RefreshInterval     time.Duration `json:"refresh_interval" yaml:"RefreshInterval"`
	ViewRefreshInterval time.Duration `json:"view_refresh_interval" yaml:"ViewRefreshInterval"`
	// If more than zero enables line animation. Defaults to zero.
	ViewAnimationInterval time.Duration `json:"view_animation_interval" yaml:"ViewAnimationInterval"`
	// The title of the monitor HTML document.
	ViewTitle string `json:"view_title" yaml:"ViewTitle"`
}

Options holds the optional fields for the Monitor structure.

type Stats

type Stats struct {
	PIDCPU   float64 `json:"pid_cpu" yaml:"PIDCPU"`
	PIDRAM   uint64  `json:"pid_ram" yaml:"PIDRAM"`
	PIDConns int64   `json:"pid_conns" yaml:"PIDConns"`

	OSCPU      float64 `json:"os_cpu" yaml:"OSCPU"`
	OSRAM      uint64  `json:"os_ram" yaml:"OSRAM"`
	OSTotalRAM uint64  `json:"os_total_ram" yaml:"OSTotalRAM"`
	OSLoadAvg  float64 `json:"os_load_avg" yaml:"OSLoadAvg"`
	OSConns    int64   `json:"os_conns" yaml:"OSConns"`
}

Stats holds the process and operating system statistics values.

Note that each statistic has its own expvar metric that you can use to render e.g. through statsd. Available values: * pid_cpu * pid_ram * pid_conns * os_cpu * os_ram * os_total_ram * os_load_avg * os_conns

type StatsHolder

type StatsHolder struct {
	// contains filtered or unexported fields
}

StatsHolder holds and refreshes the statistics.

func (*StatsHolder) Err

func (sh *StatsHolder) Err() <-chan error

Err returns a read-only channel which may be filled with errors came from the refresh stats operation.

func (*StatsHolder) GetStats

func (sh *StatsHolder) GetStats() Stats

GetStats returns a copy of the latest stats available.

func (*StatsHolder) Stop

func (sh *StatsHolder) Stop()

Stop terminates the routine which retrieves the stats for this holder. It is a no-op if the holder was never started or it is already stopped. Other StatsHolder instances are not affected.

type Uint64

type Uint64 struct {
	// contains filtered or unexported fields
}

Uint64 completes the expvar metric interface, holds an uint64 value.

func (*Uint64) Set

func (v *Uint64) Set(value uint64)

Set sets v to value.

func (*Uint64) String

func (v *Uint64) String() string

String returns the text representation of the underline uint64 value.

func (*Uint64) Value

func (v *Uint64) Value() uint64

Value returns the underline uint64 value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL