forked from markuslindenberg/icecast_exporter
-
Notifications
You must be signed in to change notification settings - Fork 3
/
icecast_exporter.go
314 lines (277 loc) · 9.03 KB
/
icecast_exporter.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Copyright 2016 Markus Lindenberg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/json"
"flag"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
)
const (
namespace = "icecast"
iso8601 = "2006-01-02T15:04:05-0700"
)
var (
labelNames = []string{"listenurl", "server_type"}
timeFormat = iso8601
)
type ISO8601 time.Time
func (ts ISO8601) Time() time.Time {
return time.Time(ts)
}
func (ts *ISO8601) UnmarshalJSON(data []byte) error {
s := string(data)
if s == "null" || s == `""` {
*ts = ISO8601(time.Time{})
return nil
}
parsed, err := time.Parse(`"2006-01-02T15:04:05-0700"`, s)
if err != nil {
return err
}
*ts = ISO8601(parsed)
return nil
}
type IcecastTime time.Time
func (ts IcecastTime) Time() time.Time {
return time.Time(ts)
}
func (ts *IcecastTime) UnmarshalJSON(data []byte) error {
s := string(data)
if s == "null" || s == `""` {
*ts = IcecastTime(time.Time{})
return nil
}
parsed, err := time.Parse(`"`+timeFormat+`"`, s)
if err != nil {
return err
}
*ts = IcecastTime(parsed)
return nil
}
type IcecastStatusSource struct {
Listeners int `json:"listeners"`
Listenurl string `json:"listenurl"`
ServerType string `json:"server_type"`
SlowListeners int `json:"slow_listeners"`
StreamStartIso8601 ISO8601 `json:"stream_start_iso8601"`
StreamStart IcecastTime `json:"stream_start"`
}
// JSON structure if zero or multiple streams active
type IcecastStatus struct {
Icestats struct {
ServerStartIso8601 ISO8601 `json:"server_start_iso8601"`
ServerStart IcecastTime `json:"server_start"`
Source []IcecastStatusSource `json:"source,omitifempty"`
} `json:"icestats"`
}
// JSON structure if exactly one stream active
type IcecastStatusSingle struct {
Icestats struct {
ServerStartIso8601 ISO8601 `json:"server_start_iso8601"`
ServerStart IcecastTime `json:"server_start"`
Source IcecastStatusSource `json:"source"`
} `json:"icestats"`
}
// Exporter collects Icecast stats from the given URI and exports them using
// the prometheus metrics package.
type Exporter struct {
URI string
mutex sync.RWMutex
up prometheus.Gauge
totalScrapes, jsonParseFailures prometheus.Counter
serverStart prometheus.Gauge
listeners *prometheus.GaugeVec
slowListeners *prometheus.GaugeVec
streamStart *prometheus.GaugeVec
client *http.Client
}
// NewExporter returns an initialized Exporter.
func NewExporter(uri string, timeout time.Duration) *Exporter {
return &Exporter{
URI: uri,
up: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Help: "Was the last scrape of Icecast successful.",
}),
totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_total_scrapes",
Help: "Current total Icecast scrapes.",
}),
jsonParseFailures: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_json_parse_failures",
Help: "Number of errors while parsing JSON.",
}),
serverStart: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "server_start",
Help: "Timestamp of server startup.",
}),
listeners: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "listeners",
Help: "The number of currently connected listeners.",
}, labelNames),
slowListeners: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "slow_listeners",
Help: "The number of currently connected slow listeners.",
}, labelNames),
streamStart: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "stream_start",
Help: "Timestamp of when the currently active source client connected to this mount point.",
}, labelNames),
client: &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
if err := c.SetDeadline(time.Now().Add(timeout)); err != nil {
return nil, err
}
return c, nil
},
},
},
}
}
// Describe describes all the metrics ever exported by the Icecast exporter. It
// implements prometheus.Collector.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- e.up.Desc()
ch <- e.totalScrapes.Desc()
ch <- e.jsonParseFailures.Desc()
ch <- e.serverStart.Desc()
e.listeners.Describe(ch)
e.streamStart.Describe(ch)
}
// Collect fetches the stats from configured Icecast location and delivers them
// as Prometheus metrics. It implements prometheus.Collector.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
status := make(chan *IcecastStatus)
go e.scrape(status)
e.mutex.Lock() // To protect metrics from concurrent collects.
defer e.mutex.Unlock()
e.listeners.Reset()
e.streamStart.Reset()
if s := <-status; s != nil {
e.serverStart.Set(float64(s.Icestats.ServerStart.Time().Unix()))
for _, source := range s.Icestats.Source {
e.listeners.WithLabelValues(source.Listenurl, source.ServerType).Set(float64(source.Listeners))
e.slowListeners.WithLabelValues(source.Listenurl, source.ServerType).Set(float64(source.SlowListeners))
switch timeFormat {
case iso8601:
e.streamStart.WithLabelValues(source.Listenurl, source.ServerType).Set(float64(source.StreamStartIso8601.Time().Unix()))
default:
e.streamStart.WithLabelValues(source.Listenurl, source.ServerType).Set(float64(source.StreamStart.Time().Unix()))
}
}
}
ch <- e.up
ch <- e.totalScrapes
ch <- e.jsonParseFailures
ch <- e.serverStart
e.listeners.Collect(ch)
e.slowListeners.Collect(ch)
e.streamStart.Collect(ch)
}
func (e *Exporter) scrape(status chan<- *IcecastStatus) {
defer close(status)
e.totalScrapes.Inc()
resp, err := e.client.Get(e.URI)
if err != nil {
e.up.Set(0)
log.Errorf("Can't scrape Icecast: %v", err)
return
}
defer resp.Body.Close()
e.up.Set(1)
// Copy response body into intermediate buffer,
// so we can deserialize twice
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
e.up.Set(0)
log.Errorf("Can't ready response body: %v", err)
return
}
buf := bytes.NewBuffer(bodyBytes)
var s IcecastStatus
err = json.NewDecoder(buf).Decode(&s)
if err != nil {
// If only a single stream is active, the JSON will
// have a different format with "source" being an object
buf := bytes.NewBuffer(bodyBytes)
var s2 IcecastStatusSingle
err = json.NewDecoder(buf).Decode(&s2)
if err != nil {
log.Errorf("Can't read JSON: %v", err)
e.jsonParseFailures.Inc()
return
}
// Copy over to staus object
s.Icestats.ServerStart = s2.Icestats.ServerStart
s.Icestats.Source = []IcecastStatusSource{s2.Icestats.Source}
}
status <- &s
}
func main() {
var (
listenAddress = flag.String("web.listen-address", ":9146", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
icecastScrapeURI = flag.String("icecast.scrape-uri", "http://localhost:8000/status-json.xsl", "URI on which to scrape Icecast.")
icecastTimeFormat = flag.String("icecast.time-format", iso8601, "Time format used by Icecast.")
icecastTimeout = flag.Duration("icecast.timeout", 5*time.Second, "Timeout for trying to get stats from Icecast.")
)
flag.Parse()
// Listen to signals
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGTERM, syscall.SIGINT)
timeFormat = *icecastTimeFormat
exporter := NewExporter(*icecastScrapeURI, *icecastTimeout)
prometheus.MustRegister(exporter)
// Setup HTTP server
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Icecast Exporter</title></head>
<body>
<h1>Icecast Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
go func() {
log.Infof("Starting Server: %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}()
s := <-sigchan
log.Infof("Received %v, terminating", s)
os.Exit(0)
}