// Package metrics exposes the core's Prometheus metrics at /metrics. // // Two kinds: counters and histograms that code updates as things happen // (downloads finished, errors per site, widgets), and values read when // Prometheus scrapes (queue depth, worker heartbeats, cache and payment // counters), so they are never out of date and cost nothing in between. // // Every method is safe on a nil *Metrics, so code and tests that do not // care about metrics pass nil. package metrics import ( "context" "net/http" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/promhttp" ) const ns = "dlbot" // Queue is a snapshot of the queue. type Queue struct { Paid, Free int // OldestWait is how long the oldest queued job has waited. OldestWait time.Duration Running int Capacity int } // Worker is what the core knows about one remote worker. type Worker struct { Name string State string // active, offline, draining, revoked LastSeen time.Time Capacity int } // Sources are read at scrape time. Any of them may be nil. type Sources struct { Queue func(ctx context.Context) (Queue, error) Workers func(ctx context.Context) ([]Worker, error) // Cache returns hits, misses and bytes saved since the start. Cache func() (hits, misses, bytesSaved int64) // Invoices returns invoices created and settled since the start. Invoices func() (created, settled int64) // Lightning reports whether payments are set up, and whether the last // call to the backend worked. Lightning func() (enabled, reachable bool) // Books counts wallets whose balance disagrees with their ledger. It // reads every ledger row, so it runs at most every BooksEvery. Books func(ctx context.Context) (int, error) BooksEvery time.Duration } // Metrics holds the collectors of the core. type Metrics struct { reg *prometheus.Registry queueWait prometheus.Histogram jobs *prometheus.CounterVec errors *prometheus.CounterVec deliveries *prometheus.CounterVec widgets *prometheus.CounterVec updates *prometheus.CounterVec } // New creates the metrics with their scrape-time sources. func New(src Sources) *Metrics { m := &Metrics{ reg: prometheus.NewRegistry(), queueWait: prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: ns, Name: "queue_wait_seconds", Help: "Time a job waited in the queue before a worker took it.", Buckets: []float64{1, 5, 15, 30, 60, 120, 300, 600, 1200, 3600}, }), jobs: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Name: "jobs_finished_total", Help: "Jobs that ended, by outcome (done, failed, cancelled) and lane. A cache hit is a job done without a worker.", }, []string{"outcome", "lane"}), errors: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Name: "download_errors_total", Help: "Failed downloads by site and error class.", }, []string{"site", "code"}), deliveries: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Name: "deliveries_total", Help: "Files sent to Telegram, by how: upload, file_id (Telegram's copy), cache (a hit).", }, []string{"via"}), widgets: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Name: "widgets_total", Help: "HTML widgets sent, and ordinary messages used because sendWidget failed.", }, []string{"widget", "outcome"}), updates: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Name: "updates_total", Help: "Telegram updates handled, by type.", }, []string{"type"}), } m.reg.MustRegister(m.queueWait, m.jobs, m.errors, m.deliveries, m.widgets, m.updates, collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), &scrape{src: src}) return m } // Handler serves the metrics in the Prometheus text format. func (m *Metrics) Handler() http.Handler { return promhttp.HandlerFor(m.reg, promhttp.HandlerOpts{Timeout: 10 * time.Second}) } // Registry is for tests. func (m *Metrics) Registry() *prometheus.Registry { return m.reg } // QueueWait records how long a job waited before it started. func (m *Metrics) QueueWait(d time.Duration) { if m != nil && d >= 0 { m.queueWait.Observe(d.Seconds()) } } // JobFinished counts a job that ended. func (m *Metrics) JobFinished(outcome, lane string) { if m != nil { m.jobs.WithLabelValues(outcome, lane).Inc() } } // DownloadError counts a failed download. site should be the host name, // without "www.", so the number of series stays bounded by the sites // people use. func (m *Metrics) DownloadError(site, code string) { if m == nil { return } if site == "" { site = "unknown" } m.errors.WithLabelValues(site, code).Inc() } // Delivered counts a file sent to a requester. func (m *Metrics) Delivered(via string) { if m != nil { m.deliveries.WithLabelValues(via).Inc() } } // Widget counts a widget sent, or a fallback to an ordinary message. func (m *Metrics) Widget(widget, outcome string) { if m != nil { m.widgets.WithLabelValues(widget, outcome).Inc() } } // Update counts a Telegram update. func (m *Metrics) Update(kind string) { if m != nil { m.updates.WithLabelValues(kind).Inc() } } // scrape reads the sources when Prometheus asks. type scrape struct { src Sources mu sync.Mutex booksAt time.Time books float64 } var ( descQueued = prometheus.NewDesc(ns+"_queue_jobs", "Jobs waiting in the queue, by lane.", []string{"lane"}, nil) descOldest = prometheus.NewDesc(ns+"_queue_oldest_wait_seconds", "How long the oldest queued job has waited.", nil, nil) descRunning = prometheus.NewDesc(ns+"_jobs_running", "Jobs a worker is working on.", nil, nil) descCapacity = prometheus.NewDesc(ns+"_worker_slots", "Download slots of all connected workers.", nil, nil) descHeartbeat = prometheus.NewDesc(ns+"_worker_heartbeat_age_seconds", "Time since a remote worker was last heard from.", []string{"worker", "state"}, nil) descHits = prometheus.NewDesc(ns+"_cache_hits_total", "Requests served from the cache.", nil, nil) descMisses = prometheus.NewDesc(ns+"_cache_misses_total", "Requests that needed a download.", nil, nil) descSaved = prometheus.NewDesc(ns+"_cache_bytes_saved_total", "Download volume the cache saved.", nil, nil) descCreated = prometheus.NewDesc(ns+"_invoices_created_total", "Lightning invoices created.", nil, nil) descSettled = prometheus.NewDesc(ns+"_invoices_settled_total", "Lightning invoices paid.", nil, nil) descLNUp = prometheus.NewDesc(ns+"_lightning_up", "1 when the last call to the payment backend worked. Absent when payments are off.", nil, nil) descBooks = prometheus.NewDesc(ns+"_wallets_mismatched", "Wallets whose cached balance disagrees with their ledger. Always 0 unless something is badly wrong.", nil, nil) descScrapeErr = prometheus.NewDesc(ns+"_scrape_errors", "Sources that could not be read in this scrape.", []string{"source"}, nil) ) func (s *scrape) Describe(ch chan<- *prometheus.Desc) { for _, d := range []*prometheus.Desc{descQueued, descOldest, descRunning, descCapacity, descHeartbeat, descHits, descMisses, descSaved, descCreated, descSettled, descLNUp, descBooks, descScrapeErr} { ch <- d } } func (s *scrape) Collect(ch chan<- prometheus.Metric) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() gauge := func(d *prometheus.Desc, v float64, labels ...string) { ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, labels...) } counter := func(d *prometheus.Desc, v int64) { ch <- prometheus.MustNewConstMetric(d, prometheus.CounterValue, float64(v)) } failed := func(source string) { gauge(descScrapeErr, 1, source) } if s.src.Queue != nil { if q, err := s.src.Queue(ctx); err == nil { gauge(descQueued, float64(q.Paid), "paid") gauge(descQueued, float64(q.Free), "free") gauge(descOldest, q.OldestWait.Seconds()) gauge(descRunning, float64(q.Running)) gauge(descCapacity, float64(q.Capacity)) } else { failed("queue") } } if s.src.Workers != nil { if ws, err := s.src.Workers(ctx); err == nil { now := time.Now() for _, w := range ws { age := now.Sub(w.LastSeen).Seconds() if w.LastSeen.IsZero() { age = -1 } gauge(descHeartbeat, age, w.Name, w.State) } } else { failed("workers") } } if s.src.Cache != nil { h, mi, saved := s.src.Cache() counter(descHits, h) counter(descMisses, mi) counter(descSaved, saved) } if s.src.Invoices != nil { c, st := s.src.Invoices() counter(descCreated, c) counter(descSettled, st) } if s.src.Books != nil { s.mu.Lock() every := s.src.BooksEvery if every <= 0 { every = 10 * time.Minute } if s.booksAt.IsZero() || time.Since(s.booksAt) > every { if n, err := s.src.Books(ctx); err == nil { s.books, s.booksAt = float64(n), time.Now() } else { failed("books") } } if !s.booksAt.IsZero() { gauge(descBooks, s.books) } s.mu.Unlock() } if s.src.Lightning != nil { if enabled, up := s.src.Lightning(); enabled { v := 0.0 if up { v = 1 } gauge(descLNUp, v) } } } // WorkerSource is what a standalone worker reports about itself. type WorkerSource struct { Active func() int Capacity func() int LastContact func() (time.Time, bool) Outcomes func() map[string]int64 YtDlp func() string } // WorkerHandler serves a worker's own metrics. A worker has no database // and no secrets beyond its token; these numbers are all it knows. func WorkerHandler(src WorkerSource) http.Handler { reg := prometheus.NewRegistry() reg.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), &workerScrape{src}) return promhttp.HandlerFor(reg, promhttp.HandlerOpts{Timeout: 5 * time.Second}) } var ( descWActive = prometheus.NewDesc(ns+"_worker_active_jobs", "Downloads running on this worker.", nil, nil) descWCap = prometheus.NewDesc(ns+"_worker_capacity", "Downloads this worker runs at once.", nil, nil) descWContact = prometheus.NewDesc(ns+"_worker_core_contact_age_seconds", "Time since the core last answered this worker.", nil, nil) descWAuth = prometheus.NewDesc(ns+"_worker_token_rejected", "1 when the core rejected this worker's token.", nil, nil) descWJobs = prometheus.NewDesc(ns+"_worker_jobs_total", "Jobs this worker finished, by outcome.", []string{"outcome"}, nil) descWYtDlp = prometheus.NewDesc(ns+"_worker_ytdlp_info", "The yt-dlp version this worker runs.", []string{"version"}, nil) ) type workerScrape struct{ src WorkerSource } func (s *workerScrape) Describe(ch chan<- *prometheus.Desc) { for _, d := range []*prometheus.Desc{descWActive, descWCap, descWContact, descWAuth, descWJobs, descWYtDlp} { ch <- d } } func (s *workerScrape) Collect(ch chan<- prometheus.Metric) { g := func(d *prometheus.Desc, v float64, l ...string) { ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, l...) } if s.src.Active != nil { g(descWActive, float64(s.src.Active())) } if s.src.Capacity != nil { g(descWCap, float64(s.src.Capacity())) } if s.src.LastContact != nil { last, rejected := s.src.LastContact() age := -1.0 if !last.IsZero() && last.Unix() > 0 { age = time.Since(last).Seconds() } g(descWContact, age) v := 0.0 if rejected { v = 1 } g(descWAuth, v) } if s.src.Outcomes != nil { for k, v := range s.src.Outcomes() { ch <- prometheus.MustNewConstMetric(descWJobs, prometheus.CounterValue, float64(v), k) } } if s.src.YtDlp != nil { if v := s.src.YtDlp(); v != "" { g(descWYtDlp, 1, v) } } }