-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
106 lines (90 loc) · 2.22 KB
/
setup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package prommetrics
import (
"regexp"
"sync"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/prometheus/client_golang/prometheus"
)
// Init initializes the module
func init() {
caddy.RegisterModule(Metrics{})
httpcaddyfile.RegisterHandlerDirective("prometheus", parseCaddyfile)
}
const defaultRegex = `^/([^/]*).*$`
var once *sync.Once = &sync.Once{}
// Metrics holds the prometheus configuration.
type Metrics struct {
regex string
// subsystem?
compiledRegex *regexp.Regexp
observer func(*observed)
}
// CaddyModule returns the Caddy module information.
func (Metrics) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.prometheus",
New: func() caddy.Module {
return &Metrics{
observer: observe,
}
},
}
}
func initMetrics() {
define("")
prometheus.MustRegister(requestCount)
prometheus.MustRegister(requestDuration)
prometheus.MustRegister(responseLatency)
prometheus.MustRegister(responseSize)
prometheus.MustRegister(responseStatus)
}
// Provision implements caddy.Provisioner.
func (m *Metrics) Provision(ctx caddy.Context) error {
once.Do(initMetrics)
if len(m.regex) == 0 {
m.regex = defaultRegex
}
m.compiledRegex = regexp.MustCompile(m.regex)
return nil
}
// Validate implements caddy.Validator.
func (m Metrics) Validate() error {
return nil
}
// UnmarshalCaddyfile expects the following syntax:
//
// prometheus {
// regex ^/([^/]*).*$
// }
// Or just:
//
// prometheus
//
func (m *Metrics) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
args := d.RemainingArgs()
if len(args) > 0 {
return d.Errf("prometheus: unexpected args: %v", args)
}
for d.NextBlock(0) {
switch d.Val() {
case "regex":
if !d.Args(&m.regex) {
return d.ArgErr()
}
default:
return d.Errf("prometheus: unknown item: %s", d.Val())
}
}
}
return nil
}
// parseCaddyfile unmarshals tokens from h into a new Middleware.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m Metrics
err := m.UnmarshalCaddyfile(h.Dispenser)
return m, err
}