-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
238 lines (193 loc) · 5.56 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
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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/google/go-github/v53/github"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/oauth2"
)
type PR struct {
Number int
Labels []*github.Label
User string
RequestedReviewers []*github.User
Repo string
CreatedAt time.Time
}
var (
//nolint:gochecknoglobals
PullRequestCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "github_pr",
Subsystem: "prometheus_exporter",
Name: "pull_request_count",
Help: "Number of Pull Requests",
},
[]string{"number", "label", "author", "reviewer", "repo", "lifetime_status"},
)
)
func main() {
interval, err := getInterval()
if err != nil {
log.Fatal(err)
}
prometheus.MustRegister(PullRequestCount)
http.Handle("/metrics", promhttp.Handler())
go func() {
ticker := time.NewTicker(time.Duration(interval) * time.Second)
// register at first time
err := snapshot()
if err != nil {
log.Fatal(err)
}
// register metrics as background
for range ticker.C {
err := snapshot()
if err != nil {
log.Fatal(err)
}
}
}()
log.Fatal(http.ListenAndServe(":8080", nil))
}
func snapshot() error {
PullRequestCount.Reset()
githubToken, err := readGithubConfig()
if err != nil {
return fmt.Errorf("failed to read Datadog Config: %w", err)
}
repositories, err := getRepositories()
if err != nil {
return fmt.Errorf("failed to get GitHub repository name: %w", err)
}
repositoryList := parseRepositories(repositories)
prs, err := getPullRequests(githubToken, repositoryList)
if err != nil {
return fmt.Errorf("failed to get PullRequests: %w", err)
}
prInfos := getPRInfos(prs)
lifetimeStaleDays, err := getLifetimeStaleDays()
if err != nil {
return fmt.Errorf("failed to get lifetime stale days: %w", err)
}
staleThresholdTime := time.Now().Add(-time.Hour * 24 * time.Duration(lifetimeStaleDays))
for _, prInfo := range prInfos {
labelsTag := make([]string, len(prInfo.Labels))
for i, label := range prInfo.Labels {
labelsTag[i] = *label.Name
}
reviewersTag := make([]string, len(prInfo.RequestedReviewers))
for i, reviewer := range prInfo.RequestedReviewers {
reviewersTag[i] = *reviewer.Login
}
lifetimeStatus := "ok"
if prInfo.CreatedAt.Before(staleThresholdTime) {
lifetimeStatus = "stale"
}
labels := prometheus.Labels{
"number": strconv.Itoa(prInfo.Number),
"label": strings.Join(labelsTag, ","),
"author": prInfo.User,
"reviewer": strings.Join(reviewersTag, ","),
"repo": prInfo.Repo,
"lifetime_status": lifetimeStatus,
}
PullRequestCount.With(labels).Set(1)
}
return nil
}
func getLifetimeStaleDays() (int, error) {
const defaultLifetimeStaleDays = 14
lifetimeStaleDays := os.Getenv("LIFETIME_STALE_DAYS")
if len(lifetimeStaleDays) == 0 {
return defaultLifetimeStaleDays, nil
}
integerLifetimeStaleDays, err := strconv.Atoi(lifetimeStaleDays)
if err != nil {
return 0, fmt.Errorf("failed to convert lifetimeStaleDays: %w", err)
}
return integerLifetimeStaleDays, nil
}
func getInterval() (int, error) {
const defaultGithubAPIIntervalSecond = 300
githubAPIInterval := os.Getenv("GITHUB_API_INTERVAL")
if len(githubAPIInterval) == 0 {
return defaultGithubAPIIntervalSecond, nil
}
integerGithubAPIInterval, err := strconv.Atoi(githubAPIInterval)
if err != nil {
return 0, fmt.Errorf("failed to read Datadog Config: %w", err)
}
return integerGithubAPIInterval, nil
}
func readGithubConfig() (string, error) {
githubToken := os.Getenv("GITHUB_TOKEN")
if len(githubToken) == 0 {
return "", fmt.Errorf("missing environment variable: GITHUB_TOKEN")
}
return githubToken, nil
}
func getPullRequests(githubToken string, githubRepositories []string) ([]*github.PullRequest, error) {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
ctx := context.Background()
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
const perPage = 100
opt := &github.PullRequestListOptions{
ListOptions: github.ListOptions{PerPage: perPage},
}
prs := []*github.PullRequest{}
allPrsInRepo := []*github.PullRequest{}
for _, githubRepository := range githubRepositories {
repo := strings.Split(githubRepository, "/")
org := repo[0]
name := repo[1]
for {
prsInRepo, resp, err := client.PullRequests.List(ctx, org, name, opt)
if err != nil {
return nil, fmt.Errorf("failed to get GitHub Pull Requests: %w", err)
}
allPrsInRepo = append(allPrsInRepo, prsInRepo...)
if resp.NextPage == 0 {
opt.Page = 0
break
}
opt.Page = resp.NextPage
}
prs = append(prs, allPrsInRepo...)
}
return prs, nil
}
func getRepositories() (string, error) {
githubRepositories := os.Getenv("GITHUB_REPOSITORIES")
if len(githubRepositories) == 0 {
return "", fmt.Errorf("missing environment variable: GITHUB_REPOSITORIES")
}
return githubRepositories, nil
}
func parseRepositories(repositories string) []string {
return strings.Split(repositories, ",")
}
func getPRInfos(prs []*github.PullRequest) []PR {
prInfos := make([]PR, len(prs))
for i, pr := range prs {
repos := strings.Split(pr.GetURL(), "/")
prInfos[i] = PR{
Number: pr.GetNumber(),
Labels: pr.Labels,
User: pr.User.GetLogin(),
RequestedReviewers: pr.RequestedReviewers,
Repo: repos[4] + "/" + repos[5],
CreatedAt: *pr.CreatedAt.GetTime(),
}
}
return prInfos
}