Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option for only exporting varnish metrics #21

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions extra_key_lables.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

type extraLabelValues map[string]string

func (exlv extraLabelValues) getVal(label string) (string, bool) {
val, ok := exlv[label]
if ok {
return val, ok
} else {
return "", false
}
}

func (exlv extraLabelValues) getLabelValues() map[string]string {
return map[string]string(exlv)
}

func (exlv extraLabelValues) add(key string, val string) bool {
oldval, ok := exlv[key]
if ok {
if oldval == val {
return false
}
}
exlv[key] = val
return true
}

func newExtraLabelValues() extraLabelValues {
ex := make(map[string]string)
return extraLabelValues(ex)
}
47 changes: 36 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
Expand All @@ -19,15 +20,16 @@ var (
VersionHash string
VersionDate string

PrometheusExporter = NewPrometheusExporter()
VarnishVersion = NewVarnishVersion()
ExitHandler = &exitHandler{}
VarnishVersion = NewVarnishVersion()
ExitHandler = &exitHandler{}
exlv = newExtraLabelValues()

StartParams = &startParams{
ListenAddress: ":9131", // Reserved and publicly announced at https://github.com/prometheus/prometheus/wiki/Default-port-allocations
Path: "/metrics",
VarnishstatExe: "varnishstat",
Params: &varnishstatParams{},
Nogo: true,
}
logger *log.Logger
)
Expand All @@ -39,10 +41,14 @@ type startParams struct {
VarnishstatExe string
Params *varnishstatParams

Verbose bool
NoExit bool
Test bool
Raw bool
Verbose bool
NoExit bool
Test bool
Raw bool
Nogo bool
VarnishAddress string
Environment string
NeedEnv bool
}

type varnishstatParams struct {
Expand Down Expand Up @@ -84,6 +90,10 @@ func init() {
flag.BoolVar(&StartParams.Verbose, "verbose", StartParams.Verbose, "Verbose logging.")
flag.BoolVar(&StartParams.Test, "test", StartParams.Test, "Test varnishstat availability, prints available metrics and exits.")
flag.BoolVar(&StartParams.Raw, "raw", StartParams.Test, "Raw stdout logging without timestamps.")
flag.BoolVar(&StartParams.Nogo, "no-go-metrics", StartParams.Nogo, "Don't export go runtime and http handler metrics")
flag.StringVar(&StartParams.VarnishAddress, "varnish-address", "127.0.0.1", "Ip of the varnish process")
flag.StringVar(&StartParams.Environment, "environment", "production", "Environment indicator: stage, dev, production etc.")
flag.BoolVar(&StartParams.NeedEnv, "envlabelneeded", false, "Need environment, varnish addressed details label")

flag.Parse()

Expand Down Expand Up @@ -111,19 +121,26 @@ func init() {
}

func main() {
var exporter *prometheusExporter

if b, err := json.MarshalIndent(StartParams, "", " "); err == nil {
logInfo("%s %s %s", ApplicationName, getVersion(false), b)
} else {
logFatal(err.Error())
}
if StartParams.NeedEnv {
exlv.add("addr", StartParams.VarnishAddress)
exlv.add("env", StartParams.Environment)
}

// Initialize
if err := VarnishVersion.Initialize(); err != nil {
ExitHandler.Errorf("Varnish version initialize failed: %s", err.Error())
}
if VarnishVersion.Valid() {
logInfo("Found varnishstat %s", VarnishVersion)
if err := PrometheusExporter.Initialize(); err != nil {
exporter = NewPrometheusExporter()
if err := exporter.Initialize(); err != nil {
logFatal("Prometheus exporter initialize failed: %s", err.Error())
}
}
Expand Down Expand Up @@ -158,7 +175,17 @@ func main() {
// Start serving
logInfo("Server starting on %s with metrics path %s", StartParams.ListenAddress, StartParams.Path)

prometheus.MustRegister(PrometheusExporter)
if StartParams.Nogo {
registry := prometheus.NewRegistry()
registry.Register(exporter)
handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
//metrics
http.Handle(StartParams.Path, handler)
} else {
prometheus.MustRegister(exporter)
// metrics
http.Handle(StartParams.Path, prometheus.Handler())
}

if StartParams.Path != "/" {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -179,8 +206,6 @@ func main() {
fmt.Fprintln(w, "Ok")
})
}
// metrics
http.Handle(StartParams.Path, prometheus.Handler())
logFatalError(http.ListenAndServe(StartParams.ListenAddress, nil))
}

Expand Down
20 changes: 19 additions & 1 deletion prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ type prometheusExporter struct {
}

func NewPrometheusExporter() *prometheusExporter {
extralabel_vals := exlv.getLabelValues()
if len(extralabel_vals) > 0 {
return &prometheusExporter{
up: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: exporterNamespace,
Name: "up",
Help: "Was the last scrape of varnish successful.",
ConstLabels: extralabel_vals,
}),
}
}
return &prometheusExporter{
up: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: exporterNamespace,
Expand All @@ -33,11 +44,18 @@ func NewPrometheusExporter() *prometheusExporter {
}

func (pe *prometheusExporter) Initialize() error {
constl := VarnishVersion.Labels()
extralabel_vals := exlv.getLabelValues()
if len(extralabel_vals) > 0 {
for l, v := range extralabel_vals {
constl[l] = v
}
}
pe.version = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: exporterNamespace,
Name: "version",
Help: "Varnish version information",
ConstLabels: VarnishVersion.Labels(),
ConstLabels: constl,
})
pe.version.Set(1)
return nil
Expand Down
6 changes: 5 additions & 1 deletion varnish.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,15 @@ func ScrapeVarnishFrom(buf []byte, ch chan<- prometheus.Metric) ([]byte, error)
}
continue
}

pName, pDescription, pLabelKeys, pLabelValues := computePrometheusInfo(vName, vGroup, vIdentifier, vDescription)

descKey := pName + "_" + strings.Join(pLabelKeys, "_")
pDesc := DescCache.Desc(descKey)
extra_label_vals := exlv.getLabelValues()
for l, v := range extra_label_vals {
pLabelKeys = append(pLabelKeys, l)
pLabelValues = append(pLabelValues, v)
}
if pDesc == nil {
pDesc = DescCache.Set(descKey, prometheus.NewDesc(
pName,
Expand Down