-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
124 lines (102 loc) · 2.52 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
type collector struct{}
const minutesBeforeCheck = 55 * time.Minute
var (
d []Count
lastChecked time.Time
)
func (c collector) Describe(ch chan<- *prometheus.Desc) {
}
func (c collector) Collect(ch chan<- prometheus.Metric) {
if len(d) == 0 || time.Now().After(lastChecked.Add(minutesBeforeCheck)) {
d = CallAPI()
lastChecked = time.Now()
}
for _, m := range d {
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc(prometheus.BuildFQName("circleci", "deploys", "per_day"), "deploys per day", []string{"date"}, nil),
prometheus.CounterValue,
float64(m.Deploys),
m.Date,
)
}
}
type Response struct {
NextPageToken string `json:"next_page_token"`
Items []Items `json:"items"`
}
type Items struct {
Id string `json:"id"`
Status string `json:"status"`
Duration int `json:"duration"`
CreatedAt time.Time `json:"created_at"`
StoppedAt time.Time `json:"stopped_at"`
CreditsUsed int `json:"credits_used"`
}
type Count struct {
Date string
Deploys int
}
func CallAPI() []Count {
c := []Count{}
now := time.Now()
start := now.AddDate(0, 0, -14)
for d := start; d.After(now) == false; d = d.AddDate(0, 0, 1) {
c = append(c, Count{d.Format("01-02-2006 Mon"), 0})
}
urls := os.Getenv("URL")
if urls != "" {
for _, u := range strings.Split(urls, ", ") {
req, _ := http.NewRequest("GET", u, nil)
token := "Basic " + os.Getenv("AUTH_TOKEN")
req.Header.Set("Authorization", token)
client := new(http.Client)
resp, _ := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
log.Fatal(err)
}
apiResponse := Response{}
jsonErr := json.Unmarshal(body, &apiResponse)
if jsonErr != nil {
log.Fatal(jsonErr)
}
for _, m := range apiResponse.Items {
i := contains(c, m.CreatedAt.Format("01-02-2006 Mon"))
if i != -1 {
c[i].Deploys = c[i].Deploys + 1
}
}
}
}
return c
}
func contains(s []Count, e string) int {
for i, a := range s {
if a.Date == e {
return i
}
}
return -1
}
var addr = flag.String("listen-address", ":9179", "The address to listen on for HTTP requests.")
func main() {
flag.Parse()
var c collector
prometheus.MustRegister(c)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(*addr, nil))
}