*: initial commit

This commit is contained in:
Matt Layher 2016-09-07 17:12:08 -04:00
commit 1da1fc3289
No known key found for this signature in database
GPG Key ID: 77BFE531397EDE94
8 changed files with 546 additions and 0 deletions

12
.travis.yml Normal file
View File

@ -0,0 +1,12 @@
language: go
go:
- 1.7
before_install:
- go get github.com/golang/lint/golint
before_script:
- go get -d ./...
script:
- go build ./...
- golint ./...
- go vet ./...
- go test -v ./...

10
LICENSE.md Normal file
View File

@ -0,0 +1,10 @@
MIT License
===========
Copyright (C) 2016 Matt Layher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

24
README.md Normal file
View File

@ -0,0 +1,24 @@
apcupsd_exporter [![Build Status](https://travis-ci.org/mdlayher/apcupsd_exporter.svg?branch=master)](https://travis-ci.org/mdlayher/apcupsd_exporter) [![GoDoc](http://godoc.org/github.com/mdlayher/apcupsd_exporter?status.svg)](http://godoc.org/github.com/mdlayher/apcupsd_exporter)
================
Command `apcupsd_exporter` provides a Prometheus exporter for the
[apcupsd](http://www.apcupsd.org/) Network Information Server (NIS).
MIT Licensed.
Usage
-----
Available flags for `apcupsd_exporter` include:
```
$ ./apcupsd_exporter -h
Usage of ./apcupsd_exporter:
-apcupsd.addr string
address of apcupsd Network Information Server (NIS) (default ":3551")
-apcupsd.network string
network of apcupsd Network Information Server (NIS): typically "tcp", "tcp4", or "tcp6" (default "tcp")
-telemetry.addr string
address for apcupsd exporter (default ":9162")
-telemetry.path string
URL path for surfacing collected metrics (default "/metrics")
```

79
apcupsdexporter.go Normal file
View File

@ -0,0 +1,79 @@
// Package apcupsdexporter provides the Exporter type used in the
// apcupsd_exporter Prometheus exporter.
package apcupsdexporter
import (
"log"
"github.com/mdlayher/apcupsd"
"github.com/prometheus/client_golang/prometheus"
)
const (
// namespace is the top-level namespace for this apcupsd exporter.
namespace = "apcupsd"
)
// An Exporter is a Prometheus exporter for apcupsd metrics.
// It wraps all apcupsd metrics collectors and provides a single global
// exporter which can serve metrics.
//
// It implements the prometheus.Collector interface in order to register
// with Prometheus.
type Exporter struct {
clientFn ClientFunc
}
var _ prometheus.Collector = &Exporter{}
// A ClientFunc is a function which can return an apcupsd NIS client.
// ClientFuncs are invoked on each Prometheus scrape, so that connections
// can be short-lived and less likely to time out or fail.
type ClientFunc func() (*apcupsd.Client, error)
// New creates a new Exporter which collects metrics by creating a apcupsd
// client using the input ClientFunc.
func New(fn ClientFunc) *Exporter {
return &Exporter{
clientFn: fn,
}
}
// Describe sends all the descriptors of the collectors included to
// the provided channel.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
e.withCollectors(func(cs []prometheus.Collector) {
for _, c := range cs {
c.Describe(ch)
}
})
}
// Collect sends the collected metrics from each of the collectors to
// prometheus.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.withCollectors(func(cs []prometheus.Collector) {
for _, c := range cs {
c.Collect(ch)
}
})
}
// withCollectors sets up an apcupsd client and creates a set of prometheus
// collectors. It invokes the input closure and then cleans up after the
// closure returns.
func (e *Exporter) withCollectors(fn func(cs []prometheus.Collector)) {
c, err := e.clientFn()
if err != nil {
log.Printf("[ERROR] error creating apcupsd client: %v", err)
return
}
cs := []prometheus.Collector{
NewUPSCollector(c),
}
fn(cs)
_ = c.Close()
}

33
apcupsdexporter_test.go Normal file
View File

@ -0,0 +1,33 @@
package apcupsdexporter
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/prometheus/client_golang/prometheus"
)
func testCollector(t *testing.T, collector prometheus.Collector) []byte {
if err := prometheus.Register(collector); err != nil {
t.Fatalf("failed to register Prometheus collector: %v", err)
}
defer prometheus.Unregister(collector)
promServer := httptest.NewServer(prometheus.Handler())
defer promServer.Close()
resp, err := http.Get(promServer.URL)
if err != nil {
t.Fatalf("failed to GET data from prometheus: %v", err)
}
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read server response: %v", err)
}
return buf
}

View File

@ -0,0 +1,50 @@
// Command apcupsd_exporter provides a Prometheus exporter for apcupsd.
package main
import (
"flag"
"log"
"net/http"
"github.com/mdlayher/apcupsd"
"github.com/mdlayher/apcupsd_exporter"
"github.com/prometheus/client_golang/prometheus"
)
var (
telemetryAddr = flag.String("telemetry.addr", ":9162", "address for apcupsd exporter")
metricsPath = flag.String("telemetry.path", "/metrics", "URL path for surfacing collected metrics")
apcupsdAddr = flag.String("apcupsd.addr", ":3551", "address of apcupsd Network Information Server (NIS)")
apcupsdNetwork = flag.String("apcupsd.network", "tcp", `network of apcupsd Network Information Server (NIS): typically "tcp", "tcp4", or "tcp6"`)
)
func main() {
flag.Parse()
if *apcupsdAddr == "" {
log.Fatal("address of apcupsd Network Information Server (NIS) must be specified with '-apcupsd.addr' flag")
}
fn := newClient(*apcupsdNetwork, *apcupsdAddr)
prometheus.MustRegister(apcupsdexporter.New(fn))
http.Handle(*metricsPath, prometheus.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, *metricsPath, http.StatusMovedPermanently)
})
log.Printf("starting apcupsd exporter on %q for server %s://%s",
*telemetryAddr, *apcupsdNetwork, *apcupsdAddr)
if err := http.ListenAndServe(*telemetryAddr, nil); err != nil {
log.Fatalf("cannot start apcupsd exporter: %s", err)
}
}
func newClient(network string, addr string) apcupsdexporter.ClientFunc {
return func() (*apcupsd.Client, error) {
return apcupsd.Dial(network, addr)
}
}

233
upscollector.go Normal file
View File

@ -0,0 +1,233 @@
package apcupsdexporter
import (
"log"
"github.com/mdlayher/apcupsd"
"github.com/prometheus/client_golang/prometheus"
)
var _ StatusSource = &apcupsd.Client{}
// A StatusSource is a type which can retrieve UPS status information from
// apcupsd. It is implemented by *apcupsd.Client.
type StatusSource interface {
Status() (*apcupsd.Status, error)
}
// A UPSCollector is a Prometheus collector for metrics regarding an APC UPS.
type UPSCollector struct {
UPSLoadPercent *prometheus.Desc
BatteryChargePercent *prometheus.Desc
LineVolts *prometheus.Desc
LineNominalVolts *prometheus.Desc
BatteryVolts *prometheus.Desc
BatteryNominalVolts *prometheus.Desc
BatteryNumberTransfersTotal *prometheus.Desc
BatteryTimeLeftSeconds *prometheus.Desc
BatteryTimeOnSeconds *prometheus.Desc
BatteryCumulativeTimeOnSecondsTotal *prometheus.Desc
ss StatusSource
}
var _ prometheus.Collector = &UPSCollector{}
// NewUPSCollector creates a new UPSCollector.
func NewUPSCollector(ss StatusSource) *UPSCollector {
var (
labels = []string{"hostname", "ups_name", "model"}
)
return &UPSCollector{
UPSLoadPercent: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "ups_load_percent"),
"Current UPS load percentage.",
labels,
nil,
),
BatteryChargePercent: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_charge_percent"),
"Current UPS battery charge percentage.",
labels,
nil,
),
LineVolts: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "line_volts"),
"Current AC input line voltage.",
labels,
nil,
),
LineNominalVolts: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "line_nominal_volts"),
"Nominal AC input line voltage.",
labels,
nil,
),
BatteryVolts: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_volts"),
"Current UPS battery voltage.",
labels,
nil,
),
BatteryNominalVolts: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_nominal_volts"),
"Nominal UPS battery voltage.",
labels,
nil,
),
BatteryNumberTransfersTotal: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_number_transfers_total"),
"Total number of transfers to UPS battery power.",
labels,
nil,
),
BatteryTimeLeftSeconds: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_time_left_seconds"),
"Number of seconds remaining of UPS battery power.",
labels,
nil,
),
BatteryTimeOnSeconds: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_time_on_seconds"),
"Number of seconds the UPS has been providing battery power due to an AC input line outage.",
labels,
nil,
),
BatteryCumulativeTimeOnSecondsTotal: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "battery_cumulative_time_on_seconds_total"),
"Total number of seconds the UPS has provided battery power due to AC input line outages.",
labels,
nil,
),
ss: ss,
}
}
// collect begins a metrics collection task for all metrics related to an APC
// UPS.
func (c *UPSCollector) collect(ch chan<- prometheus.Metric) (*prometheus.Desc, error) {
s, err := c.ss.Status()
if err != nil {
return c.BatteryVolts, err
}
labels := []string{
s.Hostname,
s.UPSName,
s.Model,
}
ch <- prometheus.MustNewConstMetric(
c.UPSLoadPercent,
prometheus.GaugeValue,
s.LoadPercent,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryChargePercent,
prometheus.GaugeValue,
s.BatteryChargePercent,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.LineVolts,
prometheus.GaugeValue,
s.LineVoltage,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.LineNominalVolts,
prometheus.GaugeValue,
s.NominalInputVoltage,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryVolts,
prometheus.GaugeValue,
s.BatteryVoltage,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryNominalVolts,
prometheus.GaugeValue,
s.NominalBatteryVoltage,
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryNumberTransfersTotal,
prometheus.CounterValue,
float64(s.NumberTransfers),
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryTimeLeftSeconds,
prometheus.GaugeValue,
s.TimeLeft.Seconds(),
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryTimeOnSeconds,
prometheus.GaugeValue,
s.TimeOnBattery.Seconds(),
labels...,
)
ch <- prometheus.MustNewConstMetric(
c.BatteryCumulativeTimeOnSecondsTotal,
prometheus.CounterValue,
s.CumulativeTimeOnBattery.Seconds(),
labels...,
)
return nil, nil
}
// Describe sends the descriptors of each metric over to the provided channel.
// The corresponding metric values are sent separately.
func (c *UPSCollector) Describe(ch chan<- *prometheus.Desc) {
ds := []*prometheus.Desc{
c.UPSLoadPercent,
c.BatteryChargePercent,
c.LineVolts,
c.LineNominalVolts,
c.BatteryVolts,
c.BatteryNominalVolts,
c.BatteryNumberTransfersTotal,
c.BatteryTimeLeftSeconds,
c.BatteryTimeOnSeconds,
c.BatteryCumulativeTimeOnSecondsTotal,
}
for _, d := range ds {
ch <- d
}
}
// Collect sends the metric values for each metric created by the UPSCollector
// to the provided prometheus Metric channel.
func (c *UPSCollector) Collect(ch chan<- prometheus.Metric) {
if desc, err := c.collect(ch); err != nil {
log.Printf("[ERROR] failed collecting UPS metric %v: %v", desc, err)
ch <- prometheus.NewInvalidMetric(desc, err)
return
}
}

105
upscollector_test.go Normal file
View File

@ -0,0 +1,105 @@
package apcupsdexporter
import (
"regexp"
"strings"
"testing"
"time"
"github.com/mdlayher/apcupsd"
)
func TestUPSCollector(t *testing.T) {
var tests = []struct {
desc string
ss *testStatusSource
matches []*regexp.Regexp
}{
{
desc: "empty",
ss: &testStatusSource{
s: &apcupsd.Status{},
},
matches: []*regexp.Regexp{
regexp.MustCompile(`apcupsd_battery_charge_percent{hostname="",model="",ups_name=""} 0`),
},
},
{
desc: "full",
ss: &testStatusSource{
s: &apcupsd.Status{
Hostname: "a",
Model: "b",
UPSName: "c",
BatteryChargePercent: 100.0,
CumulativeTimeOnBattery: 30 * time.Second,
NominalBatteryVoltage: 12.0,
TimeLeft: 2 * time.Minute,
TimeOnBattery: 10 * time.Second,
BatteryVoltage: 13.2,
NominalInputVoltage: 120.0,
LineVoltage: 121.1,
LoadPercent: 16.0,
NumberTransfers: 1,
},
},
matches: []*regexp.Regexp{
regexp.MustCompile(`apcupsd_battery_charge_percent{hostname="a",model="b",ups_name="c"} 100`),
regexp.MustCompile(`apcupsd_battery_cumulative_time_on_seconds_total{hostname="a",model="b",ups_name="c"} 30`),
regexp.MustCompile(`apcupsd_battery_nominal_volts{hostname="a",model="b",ups_name="c"} 12`),
regexp.MustCompile(`apcupsd_battery_time_left_seconds{hostname="a",model="b",ups_name="c"} 120`),
regexp.MustCompile(`apcupsd_battery_time_on_seconds{hostname="a",model="b",ups_name="c"} 10`),
regexp.MustCompile(`apcupsd_battery_volts{hostname="a",model="b",ups_name="c"} 13.2`),
regexp.MustCompile(`apcupsd_battery_number_transfers_total{hostname="a",model="b",ups_name="c"} 1`),
regexp.MustCompile(`apcupsd_line_nominal_volts{hostname="a",model="b",ups_name="c"} 120`),
regexp.MustCompile(`apcupsd_line_volts{hostname="a",model="b",ups_name="c"} 121.1`),
regexp.MustCompile(`apcupsd_ups_load_percent{hostname="a",model="b",ups_name="c"} 16`),
},
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
out := testCollector(t, NewUPSCollector(tt.ss))
for _, m := range tt.matches {
name := metricName(t, m.String())
t.Run(name, func(t *testing.T) {
if !m.Match(out) {
t.Fatal("\toutput failed to match regex")
}
})
}
})
}
}
func metricName(t *testing.T, metric string) string {
ss := strings.Split(metric, " ")
if len(ss) != 2 {
t.Fatalf("malformed metric: %v", metric)
}
if !strings.Contains(ss[0], "{") {
return ss[0]
}
ss = strings.Split(ss[0], "{")
if len(ss) != 2 {
t.Fatalf("malformed metric: %v", metric)
}
return ss[0]
}
var _ StatusSource = &testStatusSource{}
type testStatusSource struct {
s *apcupsd.Status
}
func (ss *testStatusSource) Status() (*apcupsd.Status, error) {
return ss.s, nil
}