monitor

package
v1.0.195 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package monitor expõe um servidor HTTP de observabilidade com login, gráficos em tempo real (via SSE), histórico em ring buffer, motor de alertas configurável e endpoints pprof — tudo plugável via config.json.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateSecret

func GenerateSecret() string

GenerateSecret produz uma chave hex de 32 bytes para assinar sessões.

func HashPassword

func HashPassword(plain string) (string, error)

HashPassword gera o bcrypt para gravar no config.json.

func MetricValue

func MetricValue(s Sample, name string) (float64, bool)

MetricValue extrai um valor numérico nomeado de uma Sample. Usado pelas regras de alerta para resolver "metric": "goroutines" → s.Goroutines.

Types

type Alert

type Alert struct {
	T        int64   `json:"t"`
	Rule     string  `json:"rule"`
	Metric   string  `json:"metric"`
	Severity string  `json:"severity"` // info, warn, critical
	Value    float64 `json:"value"`
	Message  string  `json:"message"`
}

type Alerts

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

func NewAlerts

func NewAlerts(rules []config.MonitorRule) *Alerts

func (*Alerts) Evaluate

func (a *Alerts) Evaluate(latest Sample, history []Sample) []Alert

Evaluate roda todas as regras contra a amostra mais recente. Para regras do tipo "growth" usa o histórico para comparar contra um ponto de referência dentro da janela.

func (*Alerts) History

func (a *Alerts) History() []Alert

History retorna alertas em ordem cronológica decrescente (mais recente primeiro).

func (*Alerts) SetListener

func (a *Alerts) SetListener(fn func(Alert))

SetListener registra um callback chamado a cada novo disparo.

func (*Alerts) SetRules

func (a *Alerts) SetRules(rules []config.MonitorRule)

SetRules permite atualizar as regras em runtime (ex: após edição do config.json).

type Auth

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

Auth gerencia autenticação por cookie HMAC e bloqueio por tentativas. O segredo HMAC vem do config (gerado se vazio na primeira execução).

func NewAuth

func NewAuth(secret, user, passHash string) *Auth

func (*Auth) Authenticated

func (a *Auth) Authenticated(r *http.Request) (string, bool)

Authenticated verifica o cookie de sessão e retorna o usuário se válido.

func (*Auth) Login

func (a *Auth) Login(w http.ResponseWriter, r *http.Request, user, pass string) error

Login valida user/pass, aplica throttling e bloqueio. Devolve o cookie pronto para Set-Cookie em caso de sucesso.

func (*Auth) Logout

func (a *Auth) Logout(w http.ResponseWriter, r *http.Request)

func (*Auth) Middleware

func (a *Auth) Middleware(next http.Handler) http.Handler

Middleware redireciona para /login as requisições de páginas, e devolve 401 JSON para chamadas a /api/*. Páginas autenticadas ficam disponíveis para o handler envolvido.

func (*Auth) Update

func (a *Auth) Update(user, passHash string)

Update troca usuário/senha em runtime após alteração via dashboard.

func (*Auth) User

func (a *Auth) User() string

User retorna o usuário corrente (para exibir no header).

type Collector

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

Collector coleta amostras do runtime numa cadência fixa e mantém um ring buffer com o histórico recente. É thread-safe para leituras concorrentes (SSE, /history) enquanto o ticker grava novos pontos.

func NewCollector

func NewCollector(retentionMin, intervalSec int) *Collector

func (*Collector) History

func (c *Collector) History() []Sample

History retorna as amostras na ordem cronológica (mais antiga → mais nova).

func (*Collector) Last

func (c *Collector) Last() Sample

Last retorna a amostra mais recente, ou zero-value se ainda não houve coleta.

func (*Collector) Sample

func (c *Collector) Sample() Sample

Sample lê o runtime e adiciona uma amostra ao buffer.

type Monitor

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

func New

func New(cfg *config.Config, appName string) (*Monitor, error)

New monta o monitor mas não inicia o servidor; Start faz isso.

func (*Monitor) Shutdown

func (m *Monitor) Shutdown(ctx context.Context) error

Shutdown faz o stop gracioso: fecha SSE subscribers e o servidor.

func (*Monitor) Start

func (m *Monitor) Start(ctx context.Context) error

Start inicia o ticker de coleta e o servidor HTTP. Bloqueia até erro.

type Sample

type Sample struct {
	T            int64   `json:"t"` // unix millis
	Goroutines   int     `json:"goroutines"`
	Threads      int     `json:"threads"`
	CGoCalls     int64   `json:"cgoCalls"`
	HeapAlloc    uint64  `json:"heapAlloc"`
	HeapInuse    uint64  `json:"heapInuse"`
	HeapIdle     uint64  `json:"heapIdle"`
	HeapSys      uint64  `json:"heapSys"`
	HeapReleased uint64  `json:"heapReleased"`
	HeapObjects  uint64  `json:"heapObjects"`
	StackInuse   uint64  `json:"stackInuse"`
	StackSys     uint64  `json:"stackSys"`
	Sys          uint64  `json:"sys"`
	TotalAlloc   uint64  `json:"totalAlloc"`
	NumGC        uint32  `json:"numGC"`
	GCPauseMs    float64 `json:"gcPauseMs"`    // última pausa
	GCCPUPercent float64 `json:"gcCpuPercent"` // % de CPU em GC desde o início
	AllocRate    float64 `json:"allocRate"`    // bytes/s alocados desde o sample anterior
	NextGC       uint64  `json:"nextGC"`
	LastGCMs     int64   `json:"lastGCMs"` // ms desde a última GC
}

Sample é uma fotografia do estado do runtime em um instante.

type Snapshot

type Snapshot struct {
	Sample
	Uptime     int64   `json:"uptime"`
	GoVersion  string  `json:"goVersion"`
	NumCPU     int     `json:"numCPU"`
	GOMAXPROCS int     `json:"gomaxprocs"`
	PID        int     `json:"pid"`
	Hostname   string  `json:"hostname"`
	AppName    string  `json:"appName"`
	Alerts     []Alert `json:"alerts,omitempty"`
}

Jump to

Keyboard shortcuts

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